/* Api */
import * as ArchiveApi from '@src/api/ArchiveApi';
import { createServiceReportBatch } from '@src/api/ExcelsApi';
import { createServicePrintBatch } from '@src/api/PrintApi';
import * as TaskApi from '@src/api/TaskApi.ts';
import { getRichTextContent } from '@src/api/SystemApi';
import { fetchViewportList } from '@src/api/Viewport';
/* enum */
import AuthEnum from '@model/enum/AuthEnum.ts';
import { TaskExceptionStateLabelEnum, TaskCreateMethodLabelEnum } from '@model/enum/LabelEnum.ts';
/* components */
import AdvancedSearchModal from '@src/component/AdvancedSearch/AdvancedSearchModal.vue';
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue';
import ViewportDropdown from '@src/component/ViewportDropdown/index.vue';
import TaskCommonAdvancedSearchForm from '@src/modules/task/components/list/TaskCommonAdvancedSearchForm.vue'; // 高级筛选联动外部搜索条件
import BatchEditingCustomerDialog from './components/BatchEditingCustomerDialog.vue';
import TaskMap from './components/TaskMap.vue';
import TaskTransfer from './components/TaskTransfer.vue';
import LogisticsMixin from '@src/mixins/logisticsMixin'
import baseSaveShowHandle from '@src/mixins/baseSaveMixin'
import statisticalDialog from '@src/modules/setting/task/taskAdditionalSetting/manage/components/statisticalDialog.vue'
import SpareStatisticDialog from '@src/modules/setting/task/taskAdditionalSetting/manage/components/SpareStatisticDialog.vue'
/* enum */
import { FieldTypeMappingEnum, LogisticsFieldNameMappingEnum } from '@model/enum/FieldMappingEnum';
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
import { GrayFunctionEnum } from '@model/grayFunction';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'

import { smoothLogisticsField } from '@service/LogisticsService'
/** model */
import TaskStateEnum from '@model/enum/TaskStateEnum.ts';
import { fields, selectIds, allExport, providerField, providerFields, Inquire, AbnormalList, qualityFields, FaultLibrary, customerExtendFields, connectorFields } from './TaskFieldModel';

import { LINK_REG } from '@src/model/reg';

/** utils */
import Page from '@model/Page';
import { ctiCallOut } from '@src/util/ctisdk';
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
import { getAllGrayInfo } from '@src/util/grayInfo';
import { storageGet, storageSet } from '@src/util/storage';
import { safeNewDate } from '@src/util/time';
import _, { cloneDeep, debounce } from 'lodash';
import { formatDate, useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()

import { pageTaskList } from 'pub-bbx-global/pageType/dist';
import AuthUtil from '@src/util/auth';
import { parse } from '@src/util/querystring';
import StorageUtil from '@src/util/storage.ts';
import { sessionStorageGet, sessionStorageRemove } from '@src/util/storageV2';
import { isEmpty } from '@src/util/type';
import { getRootWindowInitData } from '@src/util/window'
/* service */
import { filterExportFieldWithFormType,filterTaskExportFieldWithFormType, getFieldName, mergeFieldsWithProperty, isCurrencyField } from '@service/FieldService.ts';
import { formattedOpenDataTooltip } from '@service/OpenDataService.ts';
import {
  isNotSupportedDisplayField,
  isSystemFiled,
} from '@service/FieldService'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts';
import tourGuide from '@src/mixins/tourGuide';
import VersionMixin from '@src/mixins/versionMixin/index.ts';
import ConnectorMixin from '@src/mixins/connectorMixin';
import AiSummariesMixin from '@src/mixins/aiSummariesMixin';
import { isBasicEditionHideApi, isBasicEditionHideEvent, isBasicEditionHidePart, isBasicEditionHidePay, isBasicEditionHidePlanWork, isBasicEditionHidePrintTask, isBasicEditionHideProduct, isBasicEditionHideServe, isBasicEditionHideServiceReport, isShowBatchSendingServiceReports } from '@shb-lib/version';

/* export & import */
import { taskListExport } from '@src/api/Export';
import { taskCostListImport, taskCostListImportTem, taskListImport, taskListImportTem } from '@src/api/Import';

// advanced search
import { search as searchApi } from '@src/api/TaskApi.ts';


/* constants */
import {
  TaskSearchInputPlaceholderMap
} from '@src/modules/task/model/TaskConvertMap.ts';

import { isOpenData, openAccurateTab } from '@src/util/platform';

import { isCalendar } from '@src/util/CalendarUtil';

import AuthMixin from '@src/mixins/authMixin';

import i18n from '@src/locales'
/* util */
import { exportAlert } from '@src/util/alert';
import { formatAddress } from 'pub-bbx-utils';
/* mixins */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'
import { AISummaryMixin } from '@gpt/mixins'
/* const */
import { TABLE_HEIGHT_MIN } from '@src/model/const/Number'

const TASK_LIST_KEY = 'task_list';
const MAXCHECK = 500
// 工单引导标识
import taskV2Store from '@src/component/guide/taskV2Store';
const { TASK_GUIDE_List_FILTER } = taskV2Store
// 埋点事件对象
const TRACK_EVENT_MAP = {
  search: i18n.t('task.list.trackEvent.search'),
  moreAction: i18n.t('task.list.trackEvent.moreAction'),
  reset: i18n.t('task.list.trackEvent.reset'),
  avvancedSearch: i18n.t('task.list.trackEvent.advancedSearch'),
  columns: i18n.t('task.list.trackEvent.columns'),
};
// 列表筛选字段类型
const LIST_FILTER_FORM_TYPE = ['attachment', 'autograph', FieldTypeMappingEnum.JsCodeBlock];

const statesMap = {
  all: [], // 全部状态传空
  created: ['created', 'refused'], // 待指派
  allocated: ['allocated'], // 已指派
  accepted: ['accepted'], // 已接受
  processing: ['processing'], // 进行中
  finished: ['finished', 'costed'], // 已完成
  unfinished: [
    'created',
    'allocated',
    'accepted',
    'processing',
    'taskPool',
    'refused',
  ], // 未完成
  exception: [], // 异常工单
  offed: ['offed'], // 已取消
  closed: ['closed'], // 已关闭

  // 状体列表里没有 暂时用不到
  costed: ['costed'],
  taskPool: ['taskPoll'],
  refused: ['refused'],
};

// 工单回执特殊系统字段，可以添加到高级搜索中
const SpecifyFields = ['taskEstimatedMileage','estimatedMileage','actualMileage']

export default {
  name: 'task-list',
  inject: ['initData'],
  mixins: [
    tourGuide,
    VersionMixin,
    ThemeMixin,
    AuthMixin,
    LogisticsMixin,
    ConnectorMixin,
    VersionControlTaskMixin,
    AiSummariesMixin,
    AISummaryMixin,
    baseSaveShowHandle
  ],
  data() {
    return {
      exportStorageKey: StorageKeyEnum.TaskListExport,
      currentView: null,
      advancedSearchModalVisible: false,
      viewportSearchModel: [],
      isNewGuide:false,
      isButtonDisplayed: checkButtonDisplayed(),
      packUp:true, // true 默认展开,false收缩
      isOpenData,
      selectIds, // id
      taskView: [], // 顶部筛选列表
      otherList: [], // 其他列表
      filterData: {}, // 状态数据
      dropDownInfo: '', // 顶部下拉
      mapShow: false, // 地图预览
      planTimeType: '', // 判断计划时间展示的样式
      planStartTimeType: '', // 判断计划开始时间展示的样式
      planEndTimeType: '', // 判断计划完成时间展示的样式
      keyword_select: '', // 搜索筛选条件
      exportColumnList: [],
      viewType: '',
      selectId: 'all',
      checkImportTask: '',
      columns: [],
      columnNum: 1,
      currentTaskType: {},
      loading: false,
      multipleSelection: [],
      multipleSelectionPanelShow: false,

      tableKey: (Math.random() * 1000) >> 2,
      taskStateEnum: TaskStateEnum,
      taskStatusFields: [
        'onceOverTime',
        'onceRefused',
        'oncePaused',
        'onceRollback',
        'onceReallot',
        'oncePrinted',
        'positionException',
        'source'
      ],
      taskTypes: [
        {
          name: i18n.t('common.base.all'),
          id: '',
        },
      ],
      partField:'', // 选备件导出的自定义字段
      taskFields: [],
      taskReceiptFields: [],
      taskPublicFields: [], // 公共字段
      taskCommonFields:[], // 公共字段
      taskPage: new Page(),
      totalItems: 0,
      navWidth: window.innerWidth - 120,
      taskSearchInputPlaceholderMap: TaskSearchInputPlaceholderMap,
      task_view_list: [],
      seoSetList: [],
      exportColumns: [],
      showBj: false,
      typeHeight: '',
      stateHeight: '',
      guideSearchModelSave: false,
      guideDropdownMenu: false,
      isGuide:false,
      abnormalData: {},
      abnormals: AbnormalList,
      taskCustomExceptionNodeList: [{englishName: 'all', exceptionName: i18n.t('common.base.all')}],
      exceptionNodes: 'all', // 选择异常
      isCalendar,
      taskListExport,
      taskListImport,
      taskListImportTem,
      taskCostListImport,
      taskCostListImportTem,
      isShowImportCost: false,
      tableContainerHeight:'440px',
      headerPaddingTop: '16px',

      // collapse 状态栏折叠判断
      taskStateNeedCollapse: false, // 工单状态是否需要折叠
      taskStateCollapse: false, // 工单状态折叠
      taskTypeNeedCollapse: false, // 工单状态是否需要折叠
      taskTypeCollapse: false, // 工单类型折叠

      // advance search
      newSearchParams: {
        // page: 1, // 页码
        // pageSize: 10, // 单页数量
        keyword: '', // 关键词
        searchCondition: '', // 关键词搜索 索引条件
        templateId: null, // 工单类型
        stateList: [], // 工单状态列表
        isException: null, // 是否异常工单 1 异常工单 null: 后端才不处理异常 exceptionStates exceptionNodes
        exceptionStates: [], // 异常状态列表
        exceptionNodes: [], // 异常工单节点
        conditions: [], // 高级搜索条件 -- 非系统字段
        systemConditions: [], // 高级搜索条件 -- 系统字段

        // 创建视角
        createUser : '', // 我创建的
        executor : '', // 我负责的
        synergyId : '', // 我协同的
        currentNodeExecutorUser: '', // 我的待办
        nodeProcessedUser: '', // 我处理的
        searchNodeId: '', // 自定义节点id搜索

        whoseInfo: 'my', // 不知道干嘛用的
      },
      // 记录搜索条件
      searchList: [],
      isFlagSaveStatus: false,
      // 快捷筛选条件 提供给视图使用
      shortcutConditions: {
        tasksState: '',
        taskType: '',
        visualAngle: '',
        exceptionNodes: '',
      },
      visualAngle: 'all', // 创建视角
      // 高级筛选条件
      conditionParams: {
        conditions: [],
        systemConditions: [],
      },
      // taskPage: [], // 工单列表
      taskState: 'all', // 工单状态列表 移到计算属性中 单选方案
      // 工单状态列表 checked 暂时无用，未来如果使用多选可以选用
      taskStates: [
        { label: i18n.t('common.base.all'), value: 'all', checked: true, },
        { label: TaskStateEnum.CREATED.name, value: TaskStateEnum.CREATED.value, checked: false, },
        { label: TaskStateEnum.ALLOCATED.name, value: TaskStateEnum.ALLOCATED.value, checked: false, },
        { label: TaskStateEnum.ACCEPTED.name, value: TaskStateEnum.ACCEPTED.value, checked: false, },
        { label: TaskStateEnum.PROCESSING.name, value: TaskStateEnum.PROCESSING.value, checked: false, },
        { label: TaskStateEnum.FINISHED.name, value: TaskStateEnum.FINISHED.value, checked: false, },
        { label: TaskStateEnum.EXCEPTION.name, value: TaskStateEnum.EXCEPTION.value, checked: false, },
        { label: TaskStateEnum.UNFINISHED.name, value: TaskStateEnum.UNFINISHED.value, checked: false, },
        { label: TaskStateEnum.OFFED.name, value: TaskStateEnum.OFFED.value, checked: false, },
        { label: TaskStateEnum.CLOSED.name, value: TaskStateEnum.CLOSED.value, checked: false, },
        { label: TaskStateEnum.DRAFT.name, value: TaskStateEnum.DRAFT.value, checked: false, },
      ],
      sortModel: null, // 排序
      allGrayInfo:null,

      inCommonUse: [], // 常用字段
      richtextVisible:false,
      richtextContent:null,
      preViews: [],
      provideType: '', // 服务商查询类型
      showViewportGuide: false, // 是否显示引导页
      taskTypeObj: {}, // 工单类型的集合
      taskCardList: [],
      selectCard:{},
      taskNewFlowNode: [],// 自定义工单流程节点
      newTaskStates: [],
    };
  },
  computed: {
    /** 创建视角 */
    visualAngleList() {
      const defaultVisualAngle = [
        { label: i18n.t('common.base.all'), value: 'all' },
        { label: i18n.t('common.task.angle.create'), value: 'createUser' },
        { label: i18n.t('common.task.angle.execute'), value: 'executor' },
        { label: i18n.t('common.task.angle.synergy'), value: 'synergyId' },
      ]
      const newNodeDefaultVisualAngle = [
        { label: i18n.t('common.task.angle.currentNodeExecutorUser'), value: 'currentNodeExecutorUser' },
        { label: i18n.t('common.task.angle.nodeProcessedUser'), value: 'nodeProcessedUser' },
      ]
      return this.isHaveNodeFlowAuth ? [...defaultVisualAngle, ...newNodeDefaultVisualAngle] : defaultVisualAngle;
    },
    /** 是否开启新工单流程权限 */
    isHaveNodeFlowAuth() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskFlowExtend ?? false;
    },
    // 高级搜索customize-list
    searchCustomerList() {
      const allWithoutCommonFields = [...this.taskFields, ...this.taskReceiptFields].filter(item => !item.isCommon)
      return [...allWithoutCommonFields, ...this.taskCommonFields].sort((a, b) => a.orderId - b.orderId)
    },
    /** 公共字段 */
    commonFields(){
      return this.taskCommonFields.filter(item=>item.isCommon)
    },
    /** 是否显示归档工单按钮 */
    showGuidangBtn(){
      return this.taskState === TaskStateEnum.CLOSED.value && this.auth?.TASK_ARCHIVE === 3
    },
    /** 权限数据 */
    auth() {
      return this.initData.auth || {};
    },
    /** 获取是否开启联系人地址产品 */
    customerSetting() {
      let {
        address,
        product,
        linkman,
      } = this.currentTaskTypeCustomerFieldSetting;
      return {
        addressOn: address == true,
        productOn: product == true,
        linkmanOn: linkman == true,
      };
    },
    /** 当前工单类型客户字段设置 */
    currentTaskTypeCustomerFieldSetting() {
      let customerFields = this.taskFields.filter(
        (field) => field.formType == 'customer'
      );
      let customerField = customerFields[0];
      let customerSetting = {};

      if (customerField) {
        let setting = customerField.setting || {};
        customerSetting = setting.customerOption || {};
      }

      return customerSetting;
    },
    /** 判断呼叫中心开启电话 */
    callCenterModule() {
      return localStorage.getItem('call_center_module') && Number(localStorage.getItem('call_center_module'))
    },
    /** 是否显示更多操作按钮 */
    showMoreActionBtn() {
      return this.showImportBtn || this.isShowImportCost || this.showExportBtn || this.canTaskExport || this.batchReallotPermission || this.showBatchCreateServiceReportBtn || this.showBatchPrintBtn || this.showGuidangBtn
    },
    /** 是否显示导入按钮 */
    showImportBtn() {
      return (this.canTaskImport && !this.isExperienceEdition && this.isButtonDisplayed)
      || (this.isShowBatchCreateOrPrintReport && this.isShowBatchSendingServiceReports && !this.isBasicEditionHideServiceReport && this.batchCreateServiceReportPermission)
      || (this.isShowBatchCreateOrPrintReport && !this.isBasicEditionHidePrintTask && this.batchPrintServiceReportPermission)
    },
    /** 是否显示批量导出附加组件 */
    showExportAdditional(){
      return this.showExportBtn && !this.currentTaskType.id
    },
    /** 是否显示导出按钮 */
    showExportBtn() {
      return this.canTaskExport && this.isButtonDisplayed
    },
    /** 是否显示批量生成服务报告按钮 */
    showBatchCreateServiceReportBtn() {
      return this.isButtonDisplayed && this.isShowBatchCreateOrPrintReport && this.isShowBatchSendingServiceReports && !this.isBasicEditionHideServiceReport && this.batchCreateServiceReportPermission
    },
    /** 是否显示批量打印工单按钮 */
    showBatchPrintBtn() {
      return this.isButtonDisplayed && this.taskState !== TaskStateEnum.DRAFT.value && !this.isBasicEditionHidePrintTask && this.batchPrintServiceReportPermission
    },
    /** 导出权限 */
    exportPermission() {
      return this.canTaskImport || this.canTaskExport
    },
    canTaskImport() {
      return this.auth?.TASK_IMPORT && this.auth?.TASK_ADD
    },
    canTaskExport() {
      return this.auth?.TASK_EXPORT
    },
    // 转派条件
    exportPermissionTaskEdit() {
      return this.auth.TASK_EDIT === 3;
    },
    exportPermissionTaskBatchDispatch() {
      return this.auth.TASK_BATCH_DISPATCH;
    },
    // 批量工单转派权限
    batchReallotPermission() {
      return this.auth.TASK_BATCH_REASSIGNMENT;
    },
    // 批量打印工单权限
    batchPrintServiceReportPermission () {
      return this.auth.TASK_BATCH_PRINT === 3;
    },
    // 批量生成服务报告权限
    batchCreateServiceReportPermission () {
      return this.auth.TASK_BATCH_REPORT === 3;
    },
    /** 高级搜索面板宽度 */
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },
    /** 查看工单全部权限 */
    permissionTaskView() {
      return this.globalIsHaveUserViewDetailAuth
      // return this.auth.TASK_VIEW === 3;
    },
    /** 当前选中的工单ids */
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },
    /** 服务项目 服务内容 系统字段设置 */
    sysFieldsSetting() {
      let serviceContentFields = this.taskFields.filter(
        (field) => field.formType == 'serviceContent'
      );
      let serviceTypeFields = this.taskFields.filter(
        (field) => field.formType == 'serviceType'
      );

      let serviceContentField = serviceContentFields[0] || {};
      let serviceTypeField = serviceTypeFields[0] || {};

      let isServiceContentFieldEnabled = serviceContentField.enabled == 1;
      let isServiceTypeFieldEnabled = serviceTypeField.enabled == 1;

      return {
        hasServiceContent: isServiceContentFieldEnabled,
        hasServiceType: isServiceTypeFieldEnabled,
      };
    },
    /** 工单类型列表 */
    taskTypeList() {
      return this?.taskTypeObj?.readList || this?.initData?.taskTypeList || [];
      // return this?.taskTypeObj?.readList || [];
    },
    isOpenLinkCard() {
      return this.allGrayInfo && this.allGrayInfo[GrayFunctionEnum.LinkCard]
    },
    /** 工单列表字段 */
    taskListFields() {
      let fixedFields = fields.slice();
      // 开了连接器灰度
      if(this.isOpenLinkCard) {
        fixedFields = fixedFields.concat(connectorFields)
      }
      return []
        .concat(fixedFields)
        .filter((f) => f.formType !== 'separator' && f.formType !== 'info')
        .filter(item=>{
          if(item.fieldName == 'planTime') {
            return !this.isCalendar
          } else if(item.fieldName == 'planStartTime' || item.fieldName == 'planEndTime'){
            return this.isCalendar
          }
          return true
        })
        .map((field) => {
          
          if (field.fieldName == 'planStartTime' || field.fieldName == 'planEndTime') {
            const serverField = this.taskFieldsMap[field.fieldName];
            return {
              ...field,
              ...serverField
            }
          }

          return field;
          
        })
        .sort((a, b) => a.orderId - b.orderId);
    },
    /** 工单加节点系统字段节点负责人 */
    taskNewFlowNodeUser() {
      return this.taskNewFlowNode
        .filter(item => item.nodeType === 'normal')
        .map(item => ({
          fieldName: item.nodeBizId,
          displayName: `${this.$t('task.taskNodeUserListData', { data: item.nodeName })}`,
          isSystem: 1,
          isSearch: 1,
          formType: 'user',
          show: true,
          exportAlias: `normal_${item.nodeBizId}`
        }));
    },
    /** 工单加节点导出自定义字段 */
    taskNewFlowExportField() {
      const newFlowExportField = []
      this.taskNewFlowNode.forEach(item => {
        if(item?.fieldList?.length >0) {
          newFlowExportField.push({
            label: `${this.$t('task.taskNodeUserListInfo', { data: item.nodeName })}`,
            value: item.nodeBizId,
            columns: item.fieldList,
          });
        }
      })
      return newFlowExportField
    },
    /** 工单类型过滤后的字段 */
    taskTypeFilterFields() {
      let fields = this.taskFields.concat(this.taskReceiptFields) || [];

      const mergedFieldList = this.taskNewFlowNode.flatMap(obj => obj?.fieldList);
      const newFields = [...fields, ...mergedFieldList];

      let taskTypeFilterFields = newFields.filter((field) => {
        return (
          LIST_FILTER_FORM_TYPE.indexOf(field.formType) == -1
          && field.isSystem == 0
        )
        // return field.isSystem == 0
      });
      return taskTypeFilterFields;
    },
    taskAllFields() {
      return this.taskFields.concat(this.taskReceiptFields)
    },
    /* 是否显示 批量创建/生成服务报告 */
    isShowBatchCreateOrPrintReport() {
      return (
        this.taskState === TaskStateEnum.FINISHED.value || this.showGuidangBtn
      )
    },
    /**
     * @desscription 是否允许删除工单
     * 1. 删除工单权限
    */
    allowDelete() {
      return AuthUtil.hasAuth(this.auth, AuthEnum.TASK_DELETE)
    },

    hasCallAuth() {
      return !!getRootWindow(window).CTI
    },
    // 标准版隐藏发送服务报告功能
    isShowBatchSendingServiceReports() {
      return this._isShowBatchSendingServiceReports
    },
    // 基础版功能隐藏服务报告
    isBasicEditionHideServiceReport() {
      return isBasicEditionHideServiceReport()
    },
    // 基础版功能是否隐藏打印
    isBasicEditionHidePrintTask() {
      return isBasicEditionHidePrintTask()
    },
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct()
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay()
    },
    // 基础版功能是否隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent()
    },
    // 基础版功能是否隐藏计划任务
    isBasicEditionHidePlanWork() {
      return isBasicEditionHidePlanWork()
    },
    // 基础版功能是否隐藏api
    isBasicEditionHideApi() {
      return isBasicEditionHideApi()
    },
    // 基础版功能是否隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart()
    },
    // 基础版功能是否隐藏服务项目
    isBasicEditionHideServe() {
      return isBasicEditionHideServe()
    },
    isLimitTenant() {
      return true
    },
    /**
    * @description 是否开启云仓灰度
    */
    isCloudwarehouse() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskCloudWarehouse || false
    },
    /** 
    * @description 服务商结算灰度
    */
    isTaskExportProviderSettlement() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.TASK_EXPORT_PROVIDER_SETTLEMENT || false
    },
    /** 
    * @description 是否开启服务商灰度
    */
    isProviderManager() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.providerManager || false
    },
    /**
    * @description 是否开启服务商子表单灰度
    */
    isServiceProviderSubForm() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.serviceProviderSubForm || false
    },
    /**
    * @description 是否开启故障库灰度
    */
    isFaultGrayscale(){
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.faultLibrary
    },
    /**
     * @des 海伦哲灰度判断
     */
    isHandlerGray(){
      return this.allGrayInfo && this.allGrayInfo[GrayFunctionEnum.HANDLERGRAY]
    },
    // 是否开启工单草稿灰度
    isTaskCreateHalfGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.taskCreateHalf
    },
    // 是否开启结算规则灰度
    isSettlementRuleGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.settlementRule
    },
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false
    },
    taskTypeExportStorageKey() {
      const key = this.currentTaskType?.id ? `${this.exportStorageKey}_${this.currentTaskType.id}` : this.exportStorageKey;
      return key
    },
    // 可创建的工单类型列表
    createTaskTypeList() {
      return this.taskTypeObj?.writeList || this.initData.tagTaskTypeList || []
      // return this.taskTypeObj?.writeList || []
    },
    // 获取当前表格中所有字段名
    getAllFields() {
      return this.columns.map(item => {
        return {
          formType: item.formType,
          fieldName: item.fieldName,
          displayName: item.displayName
        }
      })
    },
    // 获取当前选中的表格列表
    getCurrentFieldList() {
      return this.multipleSelection
    },
    // 获取当前选中的类型
    getCurrentType() {
      return this.currentTaskType.id
    },
    taskFieldsMap() {
      return this.taskFields.reduce((map, field) => {
        map[field.fieldName] = field;
        return map;
      }, {});
    }
  },
  filters: {
    displaySelect(value) {
      if (!value) return null;
      if (value && typeof value === 'string') {
        return value;
      }
      if (Array.isArray(value) && value.length) {
        return value.join('，');
      }
      return null;
    },
    /** 审批状态 */
    displayApprove(value) {
      return value == 0 ? i18n.t('common.task.approveStatus.noApprove') : i18n.t('common.task.approveStatus.approve')
    },
    qualityStatus(value){
      if(!value) return ''
      return (value == 'IN' || value == '保内') ? i18n.t('common.base.warranty') : i18n.t('common.base.surrender')
    }
  },
  created(){
    this.recoverCommonUse();
    this.findFastPageData(); // 页面加载选中传入数据
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.fasterPage'){
        // 接收条件数据 选中传入数据
        const {data:parseData, type} = data;
        if(type == `bbx-faster-${pageTaskList.type}`){
          this.findFastPageData(parseData); // 处理选中传入数据
          this.search(); // 查询数据
        }
      }

      // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
      if (action == 'shb.frame.activatedPage'){
        this.$nextTick(()=> {
          this.knowTableContainerHeight();
        })
      }
    });
    // 服务商灰度开启并且不是服务商人员，插入预置视图
    if(this.isProviderManager && !this.isProviderUser) {
      let providerTypes = [
        { name: i18n.t('task.list.serviceProviderCreate'), id: 'serviceProviderCreate' },
        { name: i18n.t('task.list.serviceProviderExecutor'), id: 'serviceProviderExecutor' },
      ]
      providerTypes.forEach(item=>{
        this.preViews.push({
          viewId: `task_${item.id}`,
          viewName: item.name,
          searchModel: [
            {
              fieldName: 'taskCommonSearch',
              value: {
                taskType: '',
                exceptionNodes: 'all',
                taskState: 'all',
                visualAngle: 'all',
                provideType: item.id
              },
              operator: ''
            }
          ],
          authEdit: false,
          visibleType: 1,
          module: 'task',
          isPre:true
        })
      })
    }
  },
  watch:{
    taskStates() {
      // 工单状态改变 计算折叠
      this.calcCollapse();
    },
    taskTypes() {
      // 工单类型改变 计算折叠
      this.calcCollapse();
    },
  },
  async mounted() {
    try {
      // 读取缓存 覆盖初始值
      await this.revertStorage();
    } catch (error) {
      console.error('revertStorage', error);
    }


    this.getEnabledCardList()
    this.getTaskCost()
    /** 导出权限 */
    const query = parse(window.location.search) || {};
    if(query.keyword) {
      this.newSearchParams.keyword = query.keyword
    }
    if (localStorage.getItem('task_list')) {
      if (JSON.parse(localStorage.getItem('task_list')).columnStatus && !Array.isArray(JSON.parse(localStorage.getItem('task_list')).columnStatus)) {
        localStorage.clear()
      }
      this.taskPage.pageSize = JSON.parse(localStorage.getItem('task_list')).pageSize
    }
    // 没有开启工单草稿灰度时，过滤草稿状态
    if (!this.isTaskCreateHalfGray) {
      this.taskStates = this.taskStates.filter(t => t.value != TaskStateEnum.DRAFT.value)
    }

    this.taskTypes = [...this.taskTypes, ...this.taskTypeList];
    this.currentTaskType = this.taskTypeList.length === 1 ? this.taskTypes[1] : this.taskTypes[0];

    this.getTaskCountByState();

    this.getTurnOnTaskExceptionNodeInfo()
    // 获取是否自定义导出字段 目前只有博立有数据 其它的数据为空
    this.getExpensePartField()
    // 拷贝状态视角
    this.newTaskStates = cloneDeep(this.taskStates)


    window.__exports__refresh = async () => {
      this.search();
    }

    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        this.knowTableContainerHeight()
      }, 500)
    })

    // 页面参数中有viewNo时说明是复制的视图地址
    const viewNo = query.viewNo || ''
    let viewData = {}
    if (viewNo) {
      const list = await fetchViewportList('task')
      viewData = (list || []).find(item => viewNo === item.viewNo)
    }

    // 页面初始化
    // 页面有参数时不执行search方法，因为viewportSearchModel更新后会执行一遍search
    const needSearch = (query.customerId || query.productId) ? false : true
    // 页面参数中有viewNo时直接使用chooseView方法
    viewNo && viewData && viewData.searchModel ? this.chooseView(viewData) : this.initialize(true, needSearch).then(() => {
      // 高级筛选数据处理
      // TODO: customerId是从客户详情页面传过来的，productId是从产品详情传过来的，所以直接赋值，没有用push
      if (query.customerId) {
        this.viewportSearchModel = [{
          fieldName: 'customer',
          value: [
            {
              name: query.customerName,
              id: query.customerId
            }
          ],
          operator: 'eq'
        }]
      }
      if (query.productId) {
        try {
          const product = JSON.parse(localStorage.getItem('product_detail_jump_task_list'))
          this.viewportSearchModel = [{
            fieldName: 'product',
            value: {
              serialNumber: product.serialNumber,
              name: product.name,
              customerId: product.customerId,
              id: product.id,
              customerName: product.customerName,
              type: product.type
            },
            operator: 'eq'
          }]
        } catch (e) {
          console.error('get localStorage product_detail_jump_task_list error:', e)
        }
      }
    })
    // 工单获取类型可创建可以查看列表
    await this.fetchTaskTypeList();
    if (this.taskTypeList.length === 1) {
      this.getCardDetailList(this.taskTypes[1].id);
    }

    this.getSystemGrayInfo();

    /* 检查是否还有物流剩余次数 */
    this.checkQuota()

    window.addEventListener('resize', this.calcCollapse);
    this.$once('beforeDestroy', () => window.removeEventListener('resize', this.calcCollapse));
    // 服务商灰度开启，添加引导页
    if (this.isProviderManager && !this.isProviderUser) {
      this.guideProviderFilterView();
    }
  },
  methods: {
    /** 根据工单类型id获取自定义节点和对应的表单字段 */
    async getTaskNewNodeFieldList() {
      try {
        const params = {
          taskTypeId: this.currentTaskType.id || ''
        }
        let { code, success, result = [] } = await TaskApi.getTaskNodeFieldListByTypeIds(params);
        if(code == 0) {
          const filterField = ['separator', 'info', 'relationTask', 'attachment', 'autograph']
          result.map(item => {
            item.fieldList = (item.fieldList || []).filter(f => !filterField.includes(f.formType))?.map(field => ({
              group: item.nodeBizId,
              label: field.displayName,
              field: field.fieldName,
              export: true,
              ...field
            }));
          });

          this.taskNewFlowNode = result;
          // 处理状态视角
          this.handleTaskState(result)
        }
      } catch(e) {
        console.log(e)
      } 
    },
    /** 处理状态视角 */
    handleTaskState(data) {
      const taskNewState = data.filter(node=> node.nodeType == 'normal').map(item => ({
        label: item.nodeStateName,
        value: item.nodeBizId,
        checked: false,
        nodeType: item.nodeType
      }));

      let newTaskStates = [...this.newTaskStates]; // 创建原始数组的副本
      let targetIndex = newTaskStates.findIndex(obj => obj.value === TaskStateEnum.PROCESSING.value);

      if (targetIndex !== -1) {
        newTaskStates.splice(targetIndex + 1, 0, ...taskNewState);
      }
      // 更新taskStates
      this.taskStates = newTaskStates;
      
      // 如果选中的自定节点类型状态不存在默认全选
      if(this.newSearchParams.searchNodeId && !taskNewState.some(item=>item.value == this.newSearchParams.searchNodeId)) {
        this.taskState = 'all';
        this.newSearchParams.searchNodeId = '';
      }
    },
    // ai 弹窗
    aiTask() {
      
      const firstTaskTemplateId = this.multipleSelection[0]?.templateId
      const isSameTaskType = this.multipleSelection.every(item => item?.templateId == firstTaskTemplateId)
      const isSelectedTaskType = Boolean(this.currentTaskType?.id)
      
      const isNotSameTaskType = !isSameTaskType && !isSelectedTaskType
      
      if (isNotSameTaskType) {
        this.$message.warning('目前仅支持同类型数据的摘要')
        return
      }
      
      if (this.multipleSelection?.length === 0) {
        this.$message.warning('请选择指定的工单数据')
        return 
      }
      
      this.aiSummariesDialog()
    },
    getEnabledCardList(){
      ArchiveApi.getEnabledCardList().then(res=>{
        if(res.success){
          this.taskCardList = res?.result || [];
        }
      })
    },
    exportAdditional(item){
      const inventoryNameMap = {
        [this.$t('task.detail.components.sparePartList')]: 'sparePartInventory',
        [this.$t('task.detail.components.serviceList')]: 'serveInventory',
        [this.$t('task.detail.components.materialApply')]: 'MATERIALS_INVENTORY'
      }
      this.selectCard = item;
      this.$nextTick(() => {
        if (inventoryNameMap[item.name]) {
          let inventoryTypeEnum = inventoryNameMap[item.name]
          this.$refs.spareStatisteDialog.form.inventoryTypeEnum = inventoryTypeEnum;
          this.$refs.spareStatisteDialog.openDialog()
        } else {
          this.$refs.statisticalDialog.openDialog()
        }
      })
    },
    async fetchTaskTypeList() {
      try {
        const { succ = true, status, data  } = await TaskApi.getCurrentAllTaskTypeList()
        if(succ) {
          this.taskTypeObj = data
        }
      } catch(e) {
          console.error('【fetch TaskApi.getCurrentAllTaskTypeList error】', e)
      }
    },
    openSourceBizNoTab(item) {
      const { sourceBizType, sourceBizId, sourceBizTypeId } = item
      let enumKey = ''
			let params = ''
      switch (sourceBizType) {
				case 'TASK':
          enumKey = 'PageTaskView'
					break;
				case 'EVENT':
          enumKey = 'PageEventView'
					break;
				case 'CUSTOMER':
          enumKey = 'PageCustomerView'
					break;
				case 'PRODUCT':
          enumKey = 'PageProductView'
					break;
				case 'PAAS':
				  enumKey = 'PagePaasTemplateDetail'
					params = `formId=${sourceBizTypeId}&formContentId=${sourceBizId}&processId=`;
					break;

				default:
					break;
			}
      this.openTab(enumKey, sourceBizId, params)
    },
    openTab(enumKey, key, params = '') {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum[enumKey],
        key,
        params,
        fromId
      })
    },
    // 获取富文本内容
    openRichtextVisible(row, column){
      const richtextId = row.attribute[column.field] || ''
      if(!richtextId) return
      getRichTextContent({
        ids: [richtextId],
      })
        .then(res => {
          if (res.code == 0 || res.status == 0) {
            const richtextCon = res.result[0].content ?? '';
            this.richtextContent = richtextCon;
            this.richtextVisible = true;
          } else {
            throw res;
          }
        })
        .catch(err => {
          this.$notify.error({
            title: i18n.t('task.tip.errorTip'),
            message: err.message,
            duration: 2000,
          });
        })
    },
    guideProviderFilterView() {
      if (!(storageGet(TASK_GUIDE_List_FILTER) === '1')) {
        this.showViewportGuide = true;
        this.$Guide([{
          content: i18n.t('task.tip.taskListTip1'),
          haveStep: false,
          needCover: true,
          id: 'task-task-list-view',
          domId: 'task-filter-set-1',
          finishBtn: 'OK',
        }], 0, '', (e) => {
          return new Promise((resolve, reject) => {
            if(e?.type !== 'contentClick') this.showViewportGuide = false;
            resolve()
          })
        }).create().then(res_=>{if(res_)storageSet(TASK_GUIDE_List_FILTER, '1')})
      }
    },
    getTaskCost(){
      TaskApi.getTaskCost().then(res=>{
        if(res.succ && res.data){
          this.isShowImportCost = true
        }
      })
    },

    formattedOpenDataTooltip(record = '') {
      return formattedOpenDataTooltip(record || '')
    },
    // 处理人员显示
    getUserName (value) {
      // 多选
      if (Array.isArray(value)) {
        return value.map((i) => i.displayName || i.name).join(',');
      }

      let user = value || {};
      return user.displayName || user.name;
    },
    getUserIds (value) {
      // 多选
      if (Array.isArray(value)) {
        return value.map((i) => i.staffId);
      }

      let user = value || {};
      return [user.staffId];
    },
    getRelationUserIds (value) {
      // 客户产品关联跟人有关的字段 返回的是字符串
      if(!value) return []
      return value.split(',') || [];
    },
    // 归档工单
    guidang(){
      if(!this.multipleSelection.length) return this.$message.warning(i18n.t('common.placeholder.select'));
      this.$confirm(i18n.t('task.tip.archiveTaskTip2'), i18n.t('task.taskPlaceOnFile'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning'
      }).then(()=>{
        const taskIds = this.multipleSelection.map(item=>item.id);
        ArchiveApi.archiveTask({taskIds}).then(res=>{
          if(res.code === 0){
            this.toggleSelection();
            // this.searchList();
            // 后端操作es没那么快，需要延迟一点时间才能获取归档后的数据
            setTimeout(() => {
              this.handleSearch()
              this.$message.success(i18n.t('task.tip.archiveSucceed'));
            }, 1500)
          }else{
            this.$notify({
              title: i18n.t('common.base.fail'),
              message: res.message,
              type: 'success'
            });
          }
        });
      }).catch(()=>{})
    },
    async getExpensePartField(){
      const _res = await TaskApi.getExpensePartField()
      if (_res.code == 0 && _res.result?.length) {
        _res.result.forEach(item=>{
          this.partField += `${item.fieldName},`
        })
      }
    },
    /** 工单列表拨打电话 */
    async makePhoneCall(phone, isLinkman) {
      if(!this.customerSetting.linkmanOn && isLinkman) return;
      try {
        ctiCallOut(phone) // taskType:'customer'
      } catch (error) {
        console.error(error);
      }
    },
    guideDropdownMenu_enter(){
      // if (storageGet(TASK_GUIDE_DROPDOWN_MENU) == '1') return this['guideDropdownMenu'] = false;
      // storageSet(TASK_GUIDE_DROPDOWN_MENU, '1')
    },
    previousStep() {},

    abnormalLabel(type) {
      if (!this.abnormalData.taskCustomExceptionNodeList?.length) return
      const list = this.abnormalData.taskCustomExceptionNodeList.map(item => {return item.exceptionName})
      if (list.indexOf(type) !== -1) return true
      return false
    },
    getFanWei(type){
      for(let i of this.abnormalData.taskExceptionRange){
        if(i.switch){
          if(type === i.chineseName ){
            return true
          }
        }
      }
      return false
    },
    abnormalHover(item) {
      if (!item) return
      const {overTime, isPaused, oncePaused, onceOverTime, state, onceRefused, onceReallot, onceRollback, positionException, currIsReallot, currIsRoback} = item
      const s = safeNewDate().getTime()
      const e = safeNewDate(overTime).getTime()

      let value = []
      // 超时
      if(overTime && this.abnormalLabel(i18n.t('common.task.exceptionStatus.overTime')) && s > e && this.getFanWei(this.taskStateEnum.getState(item.state))) {
        value.push(i18n.t('common.task.exceptionStatus.overTime'))
      }
      if (isPaused && this.abnormalLabel(i18n.t('common.task.exceptionStatus.pause'))) {
        value.push(i18n.t('common.task.exceptionStatus.pause'))
      }
      if (oncePaused && this.abnormalLabel(i18n.t('common.task.exceptionStatus.oncePaused'))) {
        value.push(i18n.t('common.task.exceptionStatus.oncePaused'))
      }
      if (onceOverTime && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceOverTime'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceOverTime'))
      }
      if (state === 'refused' && this.abnormalLabel(i18n.t('common.task.exceptionStatus.refused'))) {
        value.push(i18n.t('common.task.exceptionStatus.refused'))
      }
      if (onceRefused && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceRefused'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceRefused'))
      }
      if (currIsReallot && this.abnormalLabel(i18n.t('common.task.exceptionStatus.allot'))) {
        value.push(i18n.t('common.task.exceptionStatus.allot'))
      }
      if (currIsRoback && this.abnormalLabel(i18n.t('common.task.exceptionStatus.rollback'))) {
        value.push(i18n.t('common.task.exceptionStatus.rollback'))
      }
      if (onceReallot && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceAllot'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceAllot'))
      }
      if (onceRollback && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceRollback'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceRollback'))
      }
      if (state === 'offed' && this.abnormalLabel(i18n.t('common.task.exceptionStatus.offed'))) {
        value.push(i18n.t('common.task.exceptionStatus.offed'))
      }
      if (positionException && this.abnormalLabel(i18n.t('common.task.exceptionStatus.positionException'))) {
        value.push(i18n.t('common.task.exceptionStatus.positionException'))
      }

      return value

    },
    /** 异常选择 */
    checkAbnormal({englishName}){
      this.resetAdvancedConditions(); // 需求：切换快捷条件 高级搜索内保留条件但是搜索不携带
      this.exceptionNodes = englishName
      this.initPage()
      this.search()
    },
    // 获取异常节点多语言label
    getTaskExceptionStateLabel(name) {
      return TaskExceptionStateLabelEnum[name] || name
    },
    // 获取创建方式的多语言label
    getSoureceLabel(key) {
      return TaskCreateMethodLabelEnum[key] || key
    },
    /** 获取用户开启的配置节点 以及工单搜索范围 和 异常原因字段值 */
    async getTurnOnTaskExceptionNodeInfo() {
      const {success, result} = await TaskApi.getTurnOnTaskExceptionNodeInfo()
      if(success) {
        result.taskCustomExceptionNodeList.map(item => {
          item.exceptionName = this.getTaskExceptionStateLabel(item.exceptionName)
          return item
        })
        this.abnormalData = result
        this.abnormalData['hoverText'] = result.taskCustomExceptionNodeList.map(item => {return item.exceptionName}).join(',')
        this.taskCustomExceptionNodeList = [...this.taskCustomExceptionNodeList, ...result.taskCustomExceptionNodeList]

        const {taskExceptionReasonList} = result
        this.abnormals = this.abnormals.map((item, index) => {
          item.setting['isMulti'] = false
          taskExceptionReasonList.forEach(v => {
            if (item.englishName === v.englishName) {
              item.setting['dataSource'] = v.exceptionReason
            }
          })
          return item
        })
      }

    },
    nextStep() {
      this.nowGuideStep ++;
    },
    stopStep() {
      this.nowGuideStep = 5;
    },
    /**
     * 获取附件
     */
    async getCardDetailList(typeId) {
      try {
        let res = await TaskApi.getCardDetailList({
          typeId
        });

        let list = res.map((item, index) => {
          
          // 附加组件是关联工单并且开启展示系统字段处理
          if(res && res.length) {
            const targetIndex = item.fields.findIndex(f => f.formType == 'related_task' && f?.setting?.isShowSystemFields);
            if (targetIndex !== -1) {
              const targetDataArray = item.fields[targetIndex].subCardFieldList || [];
              targetDataArray.forEach(f => {
                f.fieldName = `${item.cardId}_${f.fieldName}`
              })
              item.fields.splice(targetIndex + 1, 0, ...targetDataArray);
            }
          }
          if (item.canRead) {
            let columns, endAddress = {
                displayName: i18n.t('common.base.address'),
                fieldName: 'endAddress',
              }, startAddress = {
                displayName: i18n.t('common.base.address'),
                fieldName: 'startAddress',
              }
            if (item.specialfrom === '工时记录') {
              let list = []
              // 添加固定导出参数
              item.fields.splice(item.fields.map((v, i) => {
                if (v.fieldName === 'endTime') {
                  return i + 1
                }
              }).filter(v => {
                return v
              })[0], 0, endAddress)

              item.fields.splice(item.fields.map((v, i) => {
                if (v.fieldName === 'startTime') {
                  return i + 1
                }
              }).filter(v => {
                return v
              })[0], 0, startAddress)

              item.fields.forEach(v => {
                if (v.fieldName !== 'attachment'){
                  list.push(v)
                }
              })
              list.map((v, i) => {
                if (!v.map) {
                  v.fieldName = `${item.cardId}_${v.fieldName}`
                }
              })
              item.fields = [...list, ...[{displayName: i18n.t('task.list.strokeDistance'),
                fieldName: `${item.cardId}_distance`}, {displayName: i18n.t('task.list.operator'),
                fieldName: `${item.cardId}_workingOperatorName`}, {displayName: i18n.t('task.list.operateTime'),
                fieldName: `${item.cardId}_workingOperateTime`}]]

            } else {
              item.fields = [...item.fields, ...[{displayName: i18n.t('task.list.operator'),
                fieldName: `cu_${item.cardId}`}, {displayName: i18n.t('task.list.operateTime'),
                fieldName: `ct_${item.cardId}`}]]
            }
            columns = item.fields.map((v, i) => {
              return {
                export: item.canRead,
                label: v.displayName,
                exportAlias: v.fieldName,
                ...v,
              };
            }).filter(field => {
              return filterExportFieldWithFormType(field)
            });

            let value = ''
            if(item.specialfrom == '备件清单'){
              value = 'sparePartFields'
            }else if((item.specialfrom == '服务清单')){
              value = 'serviceFields'
            }else if(item.specialfrom == '物料申领'){
              value = 'materialFields'
            }else{
              value = `annexChecked${index}`
            }

            return {
              value,
              label: `${i18n.t('task.record.taskCard')}：${item.cardName}`,
              inputType: item.inputType,
              specialfrom: item.specialfrom,
              columns,
            };
          }
        }).filter(item => {
          // 过滤连接器附加组件（TODO：连接器不用翻译）
          if (item && item.specialfrom != '连接器') {
            return item
          }
        })
        this.exportColumnList = [...this.exportColumns, ...list];
      } catch(error){
        console.error(error)
      }
    },

    /**
     * @description 选择展示模式
     */
    taskMode(type) {
      if(type === i18n.t('common.base.mapMode')) {
        this.$track.clickStat(this.$track.formatParams('TASK_LIST_MAP_MODE'));
      }

      this.mapShow = type === i18n.t('common.base.mapMode');;
      // 地图模式时默认收起
      this.packUp ? this.changePackUp() : ''
    },
    /**
     * @description 删除工单列表人员
     */
    async delTask() {
      const {
        selectedIds,
        $platform
      } = this;
      // let params = selectedIds
      //   .map((item) => {
      //     return `taskIds=${item}`;
      //   })
      //   .join('&');
      if (!selectedIds.length) {
        $platform.alert(i18n.t('task.tip.taskListTip2'));
        return;
      }
      window.TDAPP.onEvent(i18n.t('task.list.trackEvent.delete'));
      try {
        const {
          succ,
          status,
          message,
          data
        } = await TaskApi.withPart(selectedIds);
        if (succ) {
          let warningMsg = i18n.t('task.tip.taskListTip3');
          if (status) {
            warningMsg = `${message}，${warningMsg}`;
          } else if (!data.status && data.length > 0) {
            warningMsg = i18n.t('task.tip.taskListTip4');
            if (data.length <= 5) {
              warningMsg += data.join('、');
            } else {
              let ids = [];
              for (let i = 0; i < 5; i++) {
                ids.push(data[i]);
              }
              warningMsg += i18n.t('task.list.howMany', {ids: ids.join('、'), num: data.length});
            }
            warningMsg += i18n.t('task.tip.taskListTip5');
          }
          let confirm = await this.$platform.confirm(warningMsg);
          if (confirm) {
            // 删除工单
            const {
              success
            } = await TaskApi.deleteTask(selectedIds);
            if (success) {
              $platform.alert(i18n.t('common.base.deleteSuccess'));
              this.loading = true;
              // es同步问题前端加延迟
              setTimeout(() => {
                this.multipleSelection = []
                if(this.taskPage.total === this.taskPage.pageNum && selectedIds.length === this.taskPage.list.length && this.taskPage.pageNum > 1) {
                  this.taskPage.pageNum--;
                }
                this.getTaskCountByState()
                this.search();
              },1500)
            }
          }
        }
      } catch (error) {
        this.loading = false;
      }
    },

    /**
     * 顶部筛选, 状态数据展示
     */
    getTaskCountByState(searchModel = {}) {
      // 如果没有缓存时间或者超过1小时
      let now = safeNewDate().getTime();
      // const localData = JSON.parse(localStorage.getItem("getTaskCountByState"));
      // if (!localData || now - localData.date > 60 * 60 * 1000) {
      TaskApi.getTaskCountByState(searchModel).then((res) => {
        if (!res.success) return;
        const {
          created,
          refused,
          allocated,
          accepted,
          exception,
          processing,
          taskPool,
          finished,
          costed,
          offed,
          closed,
          draft,
        } = res.result;
        //插入自定义节点的统计
        const normalState = {};
        if(this.isHaveNodeFlowAuth) {
          const taskStateNum = res.result || {};
          Object.keys(taskStateNum).forEach(key => {
            if(this.taskStates.some(item => item.nodeType == 'normal' && item.value == key)){
              normalState[key] = taskStateNum[key]
            }
          })
        }
        this.filterData = {
          allocated,
          accepted,
          processing,
          exception,
          created: this._number(created) + this._number(refused),
          finished: this._number(finished) + this._number(costed),
          all:
            this._number(allocated)
            + this._number(accepted)
            + this._number(processing)
            + this._number(taskPool)
            + this._number(created)
            + this._number(refused)
            + this._number(finished)
            + this._number(costed)
            + this._number(closed)
            + this._number(offed),
          unfinished:
            this._number(created)
            + this._number(refused)
            + this._number(allocated)
            + this._number(taskPool)
            + this._number(accepted)
            + this._number(processing),
          draft,
          offed,
          closed,
          ...normalState
        };
        localStorage.setItem(
          'getTaskCountByState',
          JSON.stringify({ data: now, filterData: this.filterData })
        );
      });
      // } else {
      //   this.filterData = localData.filterData;
      // }
    },
    _number(number) {
      return number ? number : 0;
    },
    /**
     * @description 工单导入
     */
    imporTask(item) {
      this.checkImportTask = item;
      this.$refs.importCustomerModal.open();
    },
    /**
     * @description 导入费用
     */
    imporCost() {
      this.$refs.importCostModal.open();
    },
    /**
     * @description 批量编辑
     */
    Alledit() {
      const {
        currentTaskType,
        selectedIds
      } = this;
      if (!currentTaskType.id) {
        this.$platform.alert(i18n.t('common.placeholder.selectSomething', {0: i18n.t('common.task.taskType')}));
        return;
      }
      if (!selectedIds.length) {
        this.$platform.alert(i18n.t('task.tip.taskListTip6'));
        return;
      }
      window.TDAPP.onEvent(i18n.t('task.list.trackEvent.batchEdit'));
      this.$refs.batchEditingCustomerDialog.open();
    },
    /**
     * @description 工单转派
     */
    reallotBatch() {
      const {
        selectedIds
      } = this;
      if (!selectedIds.length) {
        this.$platform.alert(i18n.t('task.tip.taskListTip7'));
        return;
      }

      this.$refs.TaskTransfer.openSendMessageDialog();
    },
    /**
     * @description 批量编辑成功
     */
    updateEdit() {
      this.initialize(false);
    },
    /**
     * @description 时间戳转换
     */
    timestamp(value) {
      if (typeof value === 'number') {
        let h = value / 3600 < 0 ? 0 : parseInt(value / 3600), m;
        if (h > 0) {
          m = (value % 3600) ? Math.ceil((value % 3600) / 60) : value % 3600
        } else {
          m = Math.ceil(value / 60)
        }

        if(m > 59) {
          m = 0;
          h ++;
        }
        return i18n.t('task.list.howManyHourAndMinute', {h, m});
      }
      return ''

    },
    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 构建列
     */
    async buildColumns() {
      const localStorageData = await this.getIndexedDbData();
      const {
        paymentConfig
      } = this.initData;

      let columnStatus = []
      const storageKey = this.getTaskListStorageKey();
      if(storageKey && localStorageData[storageKey]){
        columnStatus = localStorageData[storageKey]
      }else{
        columnStatus = localStorageData.columnStatus && localStorageData.columnStatus
      }
      
      if(!columnStatus) columnStatus = []

      let localColumns = columnStatus
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          }
          return acc
        }, {});
      let taskListFields = this.filterTaskListFields();
      let fields = taskListFields.concat(this.taskTypeFilterFields);
      // 自定义节点负责人信息（插入协同人后面）
      if(this.isHaveNodeFlowAuth) {
        let targetIndex = fields.findIndex(obj => obj.fieldName === 'synergies');
        
        if (targetIndex !== -1) {
          fields.splice(targetIndex + 1, 0, ...this.taskNewFlowNodeUser);
        }
      }

      // 如果没有服务商资质则去除列表和选择列的相关信息
      if(!this.isProviderManager){
        fields = fields
          .filter(item => item.formType !== 'serviceProviderQualification')
          .filter(item => item.formType !== 'engineerQualification')
      }
      if(fields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        fields = fields.filter(val => val.formType !== 'relationForm')
      }
      // 合并质保信息
      if(this.taskFields.filter(item=>item.formType === 'quality').length){
        fields.forEach((item, index)=>{
          if(item.fieldName === 'product'){
            fields.splice(index + 1, 0, qualityFields[0], qualityFields[1], qualityFields[2])
          }
        })
      }

      // 里程字段合并
      let Mileage = this.taskFields.filter(item=>['taskEstimatedMileage','estimatedMileage','actualMileage'].includes(item.formType))
      if(Mileage.length){
        Mileage.forEach((item,index)=>{
          fields.push(item)
        })
      }

      // if (this.selectColumnState === 'exception') {
      fields = fields.concat(AbnormalList)

      // 故障库字段
      if(this.isFaultGrayscale) {
        fields = fields.concat(FaultLibrary)
      }
      // }

      fields = [...fields.filter(item=>!item.isCommon), ...this.commonFields].sort((a, b) => a.orderId - b.orderId);

      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns)
      }
      // E 高级搜索
      let columns = fields
        .filter(f => !['attachment', 'separator', 'info', 'autograph'].includes(f.formType))
        .map((field) => {
          let sortable = false;
          let minWidth = 120;

          if (['date', 'datetime', 'number', 'planStartTime', 'planEndTime'].indexOf(field.formType) >= 0) {
            sortable = 'custom';
            minWidth = 100;
          }

          if (['address'].indexOf(field.formType) >= 0) {
            minWidth = 200;
          }

          if (['level', 'updateTime', 'createUserName', 'executorName', 'state'].indexOf(field.fieldName) >= 0) {
            sortable = 'custom';
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (sortable && field.displayName.length >= 4) {
            minWidth = 125;
          }

          if (
            field.formType === 'datetime'
            || field.fieldName === 'updateTime'
            || field.fieldName === 'createTime'
          ) {
            minWidth = 160;
          }

          if (
            ['taddress', 'templateName'].indexOf(field.fieldName) >= 0
          ) {
            minWidth = 200;
          }

          if (['taskNo'].indexOf(field.fieldName) !== -1) {
            minWidth = 250;
            sortable = 'custom';
          }
          if (field.fieldName === 'customer') {
            sortable = 'custom';
            minWidth = 125;
          }
          if (field.fieldName === 'taskNo') {
            field.width = 216
          }
          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
          };
        })
        .map((col) => {
          let show = col.show === true;
          let { width } = col;
          let localField = localColumns[col.field]?.field || null;
          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            if (localField.width) {
              width = typeof localField.width == 'number'
                ? `${localField.width}px`
                : localField.width;
            }
            show = localField.show !== false;
          } else {
            show = true;
          }
          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left'

          return col;
        });

      // 根据版本号判断是否需要支付方式
      if (!paymentConfig.version) {
        columns = columns.filter((item) => {
          return item.fieldName !== 'paymentMethod';
        });
      }

      // 并本地缓存列数据至当前实例的列数据
      this.mergeLocalStorageColumnsToColumns(columns)

      this.columns = []
      this.$nextTick(() => {
        this.columns = columns;
      })
      return columns

      // this.$nextTick(() => {
      //   this.$set(this, 'columns', columns.slice())

      //   // 根据版本号判断是否需要支付方式
      //   if (!paymentConfig.version) {
      //     this.advanceds = this.advanceds.filter((item) => {
      //       return item.fieldName !== 'paymentMethod';
      //     });
      //     this.columns = this.columns.filter((item) => {
      //       return item.fieldName !== 'paymentMethod';
      //     });
      //   }
      //   // 并本地缓存列数据至当前实例的列数据
      //   this.mergeLocalStorageColumnsToColumns()

      // })
    },
    /**
     * @description 合并本地缓存列数据至当前实例的列数据
     */
    async mergeLocalStorageColumnsToColumns(columns = []) {
      const { columnStatus } = await this.getIndexedDbData()
      if (isEmpty(columnStatus)) return

      mergeFieldsWithProperty(
        columns,
        columnStatus,
        (column, localStorageDataColumnItem) => {
          // 列名不匹配则返回
          if (getFieldName(column) !== getFieldName(localStorageDataColumnItem)) return
          // 覆盖列显示状态
          column.show = Boolean(localStorageDataColumnItem.show)
          // 覆盖宽度数据
          if (localStorageDataColumnItem?.width) {
            column.width = localStorageDataColumnItem.width
          }
        }
      )
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = []

      originFields.forEach(originField => {
        let {
          fieldName
        } = originField
        let field = fieldsMap[fieldName]

        if (field) {
          let {
            index
          } = field
          fields[index] = originField
        } else {
          unsortedFields.push(originField)
        }

      })

      return fields.concat(unsortedFields)
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    // buildExportParams(checkedMap, ids) {
    //   const Params = Object.assign({}, this.params);
    //   let exportAll = !ids || !ids.length;

    //   let taskQueryInput = {
    //     ids: exportAll ? [] : ids,
    //     keyword: Params.keyword,
    //     pageSize: exportAll ? 0 : Params.pageSize,
    //     page: exportAll ? 1 : Params.pageNum,
    //     typeId: this.currentTaskType.id,
    //     ...Params.moreConditions,
    //   };

    //   let params = {
    //     taskQueryInput: JSON.stringify(taskQueryInput),
    //   };

    //   for (let key in checkedMap) {
    //     params[key] = checkedMap[key].join(",");
    //   }

    //   return params;
    // },
    /**
     * 导出子表单数据
     */
    buildSubExportData(fieldName, list = []) {
      if(list.length < 1) return {}
      return {
        [fieldName]: list
      }
    },
    /**
     * 导出数据
     */
    exportData(number, list = []) {
      const export_list = this.exportColumnList.length ? this.exportColumnList : this.exportColumns;
      let cardField = []
      if (number > 2) {

        export_list.filter((item, index) => {
          // 附加组件备件清单和服务清单过滤单独处理
          if(number === 3){
            return index > 2 && item.specialfrom !== '备件清单' && item.specialfrom !== '服务清单'
          }
          if(number === 4){
            return index > 2 && item.specialfrom == '备件清单'
          }
          if(number === 5){
            return index > 2 && item.specialfrom == '服务清单'
          }
          if(number === 6){
            return index > 2 && item.specialfrom == '物料申领'
          }

        }).forEach(v => {
          v.columns.forEach(item => {
            cardField.push(item)
          })
        })

      } else{
        //新建节点、回执，系统导出处理
        cardField = export_list.find(item=>item.value == number)?.columns || []

      }
      return cardField.map(v => {
        let bool = list.some(item => {
          if (v.exportAlias) {
            return v.exportAlias === item
          }
          return v.fieldName === item

        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const {
        sparePartFields,
        serviceFields,
        materialFields,
        receiptChecked,
        systemChecked,
        taskChecked,
        providerFields,
        serviceProviders
      } = checkedMap
      const rootWindow = getRootWindow(window);
      const {
        loginUser
      } = this.initData;
      let exportAll = !ids || !ids.length;
      const searchParams = this.buildSearchParams();
      const all = {
        ...searchParams,
        taskIds: exportAll ? null : this.selectedIds,
        tagIds: loginUser.tagIds,
        dataLevel: loginUser.authorities.TASK_VIEW,
        tenantId: JSON.parse(rootWindow._init).user?.tenantId,
      };

      let exportSearchModel = {
        typeId: this.currentTaskType.id,
      };
      let params = {
        exportSearchModel: JSON.stringify({
          ...all,
          ...{
            exportTotal: exportAll
              ? this.taskPage.totalElements : this.selectedIds.length,
          },
        }),
      };
      // 附加
      let cardFieldChecked = []
      for (let key in checkedMap) {
        if (key.indexOf('annexChecked') !== -1) {
          cardFieldChecked = [...cardFieldChecked, ...checkedMap[key]]
        }
      }
      cardFieldChecked = cardFieldChecked.filter(item => {return item})
      /** ********************* *********************/
      // 工单信息
      let export_task = this.exportData('taskChecked', taskChecked)
      // 工单拓展节点信息
      let export_taskNewNode = Object.keys(checkedMap)
        .filter(key => this.taskNewFlowNode.some(item => item.nodeBizId === key))
        .reduce((obj, key) => {
          if(checkedMap?.[key]?.length) {
            obj[key] = checkedMap[key];
          }
          return obj;
        }, {});
      // 回执信息
      let export_receipt_task = this.exportData('receiptChecked', receiptChecked)
      // 系统信息
      let export_sys_task = this.exportData('systemChecked', systemChecked)
      // 服务商信息
      let export_providerFields = providerFields
      // 附加信息
      let export_card_fiel_task = cardFieldChecked.length ? this.exportData(3, cardFieldChecked) : cardFieldChecked;
      // 备件清单
      let export_sparePartFields = this.exportData(4, sparePartFields)
      // 服务清单
      let export_serviceFields = this.exportData(5, serviceFields)
      // 物料申领
      let export_materialFields = this.exportData(6, materialFields)
      // 子表单（服务商）
      let export_subFields = this.buildSubExportData('serviceProviders', serviceProviders)

      // 子表单（回执表单）
      let export_subFieldsReceipt = {}

      // 关联表单
      if(this.taskFields.some(item => item.formType === 'relationForm')){
        const fieldNameList = this.taskFields.filter(item => item.formType === 'relationForm').map(item => item.fieldName);
        fieldNameList.forEach(item => {
          export_subFields[item] = checkedMap[item]
          export_task = export_task.filter(val => val !== item)
        })
      }

      // 回执信息子表单接口导出字段
      if(this.taskReceiptFields.some(item => item.formType === 'relationForm')){
        const fieldNameList = this.taskReceiptFields.filter(item => item.formType === 'relationForm').map(item => item.fieldName);
        fieldNameList.forEach(item => {
          export_subFieldsReceipt[item] = checkedMap[item]
        })
    }
      console.log('导出数据----附加', export_card_fiel_task)

      params['exportOneRow'] = exportOneRow
      params['data'] = exportAll ? '' : this.selectedIds.join(',');
      params['typeId'] = exportSearchModel.typeId;
      params['sparePartFields'] = export_sparePartFields;
      params['serviceFields'] = export_serviceFields;
      params['subFieldNameMap'] = export_subFields;
      params['providerFields'] = export_providerFields;
      params['subFieldNameMapReceipt'] = export_subFieldsReceipt;
      params['materialFields'] = export_materialFields;
      if(this.isHaveNodeFlowAuth) {
        params['nodeFieldMap'] = export_taskNewNode;
      }
      params['receiptChecked'] = export_receipt_task
        .map((item) => {
          if (item === 'spare_name') {
            // 添加定制客户的自定义导出备件字段
            item = `spare_name,spare_serialNumber,${this.partField}spare_type,spare_standard,spare_number,spare_cost`
          }
          if (item === 'service_name') {
            item = 'service_name,service_type,service_number,service_cost'
          }
          if (item === 'apply_material') {
            // 物料核销
            item = 'apply_material_name,apply_material_serialNumber,apply_material_property,apply_material_unit,apply_material_sn_manage,apply_material_sale_price,apply_material_out_ware_house,apply_material_out_ware_house_id,apply_material_pre_num,apply_material_sn,apply_material_warranty_status'
          }
          if (item === 'return_material') {
            // 物料返还
            item = 'return_material_name,return_material_serialNumber,return_material_property,return_material_unit,return_material_sn_manage,return_material_out_ware_house,return_material_out_ware_house_id,return_material_num,return_material_sn,return_material_way,return_material_company,return_material_code'
          }
          if (item === 'sparePartsReturnExpense') {
            // 备件返还
            item = 'return_parts_relationStandard,return_parts_type,return_parts_salePrice,return_parts_name,return_parts_serialNumber,return_parts_unit,return_parts_returnNum,return_parts_returnWarehouse,return_parts_costPrice,return_parts_description'
          }
          if (item === 'balance_total') {
            // 如果开启结算规则灰度
            if (this.isSettlementRuleGray) {
              item = ''
              params.taskSettlement =  ['ruleName', 'isFreeName', 'materialTotal', 'sparePartTotal', 'serviceTotal', 'disExpense', 'totalExpense', 'finalTotalAmount']
            } else {
              item = 'balance_total,balance_discount,balance_sum'
            }
          }
          return item;
        })
        .filter(Boolean)
        .join(',');
      params['sysChecked'] = export_sys_task
        .map((item) => {
          return item;
        })
        .join(',');
      params['checked'] = export_task
        .map((item) => {
          if (item === 'product') {
            item = 'product,productSN'
          }
          return item;
        })
        .join(',');
      params['cardFieldChecked'] = export_card_fiel_task.filter(item => {
        return item
      }).join(',')
      return params;
    },

    /**
     * @description 构建多行文本
     * @return {String}
     */
    buildTextarea(value) {
      return value
        ? value.replace(LINK_REG, (match) => {
          return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`;
        })
        : '';
    },
    /**
     * @description 工单类型改变
     */
    changeTaskType(taskType, needSearch = true) {
      this.resetAdvancedConditions(); // 需求：切换快捷条件 高级搜索内保留条件但是搜索不携带
      if (localStorage.getItem('checkedMap')) {
        localStorage.removeItem('checkedMap')
        localStorage.removeItem('checkedGroupArr')
        localStorage.removeItem('isCheckedAll')
      }

      // 选中工单类型
      this.currentTaskType = taskType;
      if(!needSearch) return
      // 初始化数据
      this.initialize(true, needSearch,'changeTaskType')
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.taskPage.totalElements > max
        ? i18n.t('common.base.tip.exportLimit', { exportLimit })
        : null;
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /**
     * @description 导出工单
     * @param {Boolean} exportAll 是否导出全部
     */
    async exportTask(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')} ${i18n.t('task.list.taskData')}.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(i18n.t('common.base.tip.exportUnChooseTip'));
        ids = this.selectedIds;
      }

      const ExportPanelComponent = this.$refs.exportPanel
      if (!ExportPanelComponent) {
        return console.warn('Caused: $refs.exportPanel is Empty')
      }

      const LocalStorageData = await this.getIndexedDbData()
      let exportCheckedData = LocalStorageData.exportCheckedData

      if (!exportCheckedData) {
        exportCheckedData = {
          checkedGroup: [],
          checkedMap: {},
          isCheckedAll: false,
          tooltip: true
        }
      }

      console.log(exportCheckedData, '导出的数据')

      ExportPanelComponent.open(ids, fileName, false, exportCheckedData)

    },
    /**
     * 下载附件
     */
    async exportAttachment(){
      const { multipleSelection, $platform, $message } = this;
      if(!multipleSelection.length){
        return $platform.alert(i18n.t('task.tip.taskListTip8'));
      }
      try{
        const taskIds = multipleSelection.map(item=>item.id);
        let { status, message } = await TaskApi.exportAttachment({taskIds});
        // $message({
        //   type:`${ status === 0 ? 'success' : 'error'}`,
        //   message
        // });
        // $platform.alert(message);
        if(status === 0){

          exportAlert(message);

        }else {
          $platform.alert(message);
        }

      }catch(err){
        console.error('下载工单附件 error:', err);
      }
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task',
        isFromSetting: false
      };
      return TaskApi.getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
          if(isCurrencyField(field)) {
            field.exportAlias = `${field.fieldName}_amount_number`
          }
        });
        // 开了连接器灰度
        if(this.isOpenLinkCard) {
          result = result.concat(connectorFields)
        }
        // if(result.filter(item=>item.formType==='quality').length){
        //   result=[...result.filter(item=>item.formType!=='quality'),...qualityFields]
        // }
        return result;
      });
    },
    // 单独获取质保字段的相关信息
    getQualityField(){
      return TaskApi.getQualityFieldApi()
        .then(result => result?.data || [])
        .catch(() => [])
    },
    /**
     * @description 获取工单回执字段列表
     * @return {Promise}
     */
    fetchTaskReceiptFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task_receipt',
        isFromSetting: false
      };
      return TaskApi.getAllFields(params).then((result) => {
        result && result.forEach((field) => {
          field.group = 'task_receipt';
          field.label = field.displayName;
          field.field = field.fieldName;
          if(isCurrencyField(field)) {
            field.exportAlias = `${field.fieldName}_amount_number`
          }
        });
        return result;
      });
    },
    /**
     * @description 获取公共字段
    */
    getCommonFields(){
      let params = {
        tableName: 'all',
        typeId: this.currentTaskType.id || '',
      };
      return TaskApi.getCommonFields(params).then((result) => {
        result && result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },

    /**
     * @description 过滤工单列表字段
     * @return {Array<TaskField>} 过滤后工单列表字段
     */
    filterTaskListFields() {
      let fields = this.taskListFields || [];
      let field = null;

      let customerSetting = this.customerSetting;
      let sysFieldsSetting = this.sysFieldsSetting;

      let newFields = [];

      for (let i = 0; i < fields.length; i++) {
        field = fields[i];

        // 未开启联系人
        if (
          !customerSetting.linkmanOn
          && (field.fieldName == 'tlmName' || field.fieldName == 'tlmPhone')
        ) {
          continue;
        }

        // 未开启地址
        if (!customerSetting.addressOn && field.fieldName == 'taddress') {
          continue;
        }

        // 未开启产品
        if (!customerSetting.productOn && field.fieldName == 'product') {
          continue;
        }

        // 服务类型
        if (
          !sysFieldsSetting.hasServiceType
          && field.fieldName == 'serviceType'
        ) {
          continue;
        }

        // 服务内容
        if (
          !sysFieldsSetting.hasServiceContent
          && field.fieldName == 'serviceContent'
        ) {
          continue;
        }

        // 基础版过滤产品、支付方式、结算时间、关联事件、曾打印字段
        if (
          this.isBasicEditionHideProduct
          && field.fieldName === 'product'
        ) {
          continue;
        }
        if (
          this.isBasicEditionHidePay
          && (field.fieldName === 'paymentMethod' || field.fieldName === 'balanceTime')
        ) {
          continue;
        }
        if (
          this.isBasicEditionHideEvent
          && field.fieldName === 'eventNo'
        ) {
          continue;
        }
        if (
          this.isBasicEditionHidePrintTask
          && field.fieldName === 'oncePrinted'
        ) {
          continue;
        }
        // 未开启服务商子表单灰度 过滤掉服务商
        if (
          !this.isServiceProviderSubForm
          && field.fieldName === 'serviceProviders'
        ) {
          continue;
        }

        newFields.push(field);
      }

      return newFields;
    },
    /**
     * @description 格式化自定义地址
     * @param {Object} row 列表行数据
     * @param {Object} column 字段数据
     * @return {String} 过滤后的地址
     */
    formatCustomizeAddress(row, column) {
      const customizeAddress = column.isSystem ? row[column.formType] : row?.attribute[column.fieldName]
      if (null == customizeAddress) return '';

      return formatAddress(customizeAddress)
    },
    /**
     * @description 格式化服务团队
     */
    formatExecutorTags(executorTags) {
      if (null == executorTags) return '';

      return executorTags.map(item => item.name).join('、');
    },
    /**
     * @description 获取本地存储数据
     * @return {Object} 本地存取数据对象
     */
    getLocalStorageData() {
      const dataStr = storageGet(TASK_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },
    /**
     * @description 获取本地db数据
     */
    getTaskListStorageKey() {
      // 视图id
      const viewId = this.taskState || 'all'
      // 工单类型id
      const taskTypeId = this.currentTaskType?.id || 'all'

      return `${viewId}_${taskTypeId}`
    },
    async getIndexedDbData() {
      let data = {}
      let taskListStorageKey = this.getTaskListStorageKey()

      try {
        data = await StorageUtil.storageGet(taskListStorageKey, {}, StorageModuleEnum.Task)
      } catch (error) {
        data = {}
        console.error('Caused ~ TaskList ~ getIndexedDbData ~ error', error)
      }

      return data
    },
    /**
     * @description 获取行的key
     * @param {Object} row 行数据
     * @return {String} key
     */
    getRowKey(row = {}) {
      return `${row.iid}${(Math.random() * 1000) >> 2}`;
    },
    /**
     * @description 表格选择操作
     * @param {Array} selection 选择的数据
     */
    handleSelection(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter((ms) =>
        this.taskPage.list.some((cs) => cs.id === ms.id)
      );

      let unSelected = this.taskPage.list.filter((c) =>
        original.every((oc) => oc.id !== c.id)
      );

      if (tv.length > MAXCHECK) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach((row) => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(i18n.t('common.base.tip.selectAtMostTip', {max: MAXCHECK}));
      }
      this.multipleSelection = tv;
      // this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    /**
     * @description 页大小改变操作
     * @param {Number} pageSize 页大小
     */
    handleSizeChange(pageSize) {
      this.saveDataToIndexedDb('pageSize', pageSize);
      this.initPage(1, pageSize);
      this.search();
    },
    /**
     * @description 初始化
     * @params isChangePage 初始化默认改变pageNum pageSize 批量编辑不改变
     */
    initialize(isChangePage = true, needSearch = true, type = 'change') {
      // 默认回到第一页 批量编辑保持当前页面
      this.loading = true;
      // 选择全部工单类型不请求获取回执表单的接口
      let subtask = [this.fetchTaskFields(), this.getCommonFields()];
      if(this.currentTaskType?.id) {
        subtask.push(this.fetchTaskReceiptFields())
      }
      if(this.isHaveNodeFlowAuth) {
        subtask.push(this.getTaskNewNodeFieldList())
      }
      return Promise.all(subtask)
        .then(async (res) => {
          // 解析基础组件 物流组件字段
          this.$set(this, 'taskFields', smoothLogisticsField(res[0] || []));
          // 解析自定义字段 物流组件字段
          this.$set(this, 'taskReceiptFields', smoothLogisticsField(res[2] || []));
          // 解析公共字段 物流组件字段
          this.$set(this, 'taskCommonFields', smoothLogisticsField(res[1] || []))
          let arr1 = res[0].find((item) => {
            return item.fieldName === 'planTime';
          });
          let arr2 = res[0].find((item) => {
            return item.fieldName === 'planStartTime';
          })
          let arr3 = res[0].find((item) => {
            return item.fieldName === 'planEndTime';
          });
          this.planTimeType = arr1?.setting.dateType || '';
          this.planStartTimeType = arr2?.setting.dateType || '';
          this.planEndTimeType = arr3?.setting.dateType || '';
          // 当前选择的工单类型是全部
          if(!this.currentTaskType.id || this.currentTaskType.name === i18n.t('common.base.all')){
            const data = await this.getQualityField()
            this.taskFields = [ ...this.taskFields, ...data ]
          }
          await this.buildColumns();
          await this.seoSet();
          await this._exportColumns();
          if(needSearch && type === 'changeTaskType') {
            isChangePage && this.initPage();
            this.search('save');
          } else if(needSearch){
            isChangePage && this.initPage();
            this.search();
          } else {
            this.loading = false;
          }
        })
        .catch((err) => {
          this.loading = false;
          console.warn(err);
        });
    },
    /**
     * @description 高级搜索里面设置的值
     */
    seoSet() {
      const {taskFields} = this
      let seoList = [];
      const excludeField = new Set(['attachment', 'autograph', i18n.t('common.form.type.taskNo'), 'taskNo', 'taskType', 'faultLibrary', 'quality']);

      for(let field of cloneDeep([...taskFields, ...this.abnormals, ...Inquire])){
        const { formType, fieldName, displayName, isSystem, setting, isSearch } = field;
        field.setting = field.setting || {};
        // 排除 非系统字段
        if(isSystem !== 1) continue;

        // 排除制定类型字段
        if([formType, fieldName, displayName].some(item => excludeField.has(item))) continue; // 过滤不需要的字段

        if(this.isBasicEditionHidePay) {
          // 基础版本 隐藏支付相关
          if (['balanceTime', 'paymentMethod'].includes(fieldName)) continue;

          // 状态去除已结算
          if(fieldName === 'state'){
            // TODO 国际化待办
            field.setting.dataSource = field.setting.dataSource?.filter(source => source !== '已结算');
          }
        }

        if (this.isBasicEditionHideEvent) {
          // 基础版本 隐藏事件相关
          if(fieldName === 'eventNo') continue;

          // 基础版创建方式过滤由事件创建字段
          if (fieldName === 'source') {
            field.setting.dataSource = field.setting.dataSource?.filter(source => source !== '由事件创建');
          }
        }

        // 基础版 隐藏打印
        if (fieldName === 'oncePrinted' && this.isBasicEditionHidePrintTask) continue;

        // 服务商子表单灰度
        if(!this.isServiceProviderSubForm) {
          if(fieldName === 'serviceProviders') continue;
        }

        if (fieldName === 'source') {
          if(this.isBasicEditionHidePlanWork) {
            // 基础版创建方式过滤计划任务创建字段
            // TODO 国际化待办
            field.setting.dataSource = field.setting.dataSource?.filter(source => source !== '计划任务创建');
          }
          if (this.isBasicEditionHideApi) {
            // 基础版创建方式过滤API创建字段
            field.setting.dataSource = field.setting.dataSource?.filter(source => source !== 'API创建');
          }
        }

        field.isNull = 1; // 高级搜索允许空值

        seoList.push(field); // 添加进列表

        if(fieldName === 'customer'){
          // 客户字段后面需要添加以下字段
          const {linkman, address, product} = setting?.customerOption || {};
          if(linkman) {
            seoList.push(customerExtendFields.tlmName)
          }
          if(address) {
            seoList.push(customerExtendFields.area, customerExtendFields.address)
          }
          if(product && !this.isBasicEditionHideProduct) {
            // 基础版本没有产品
            seoList.push(customerExtendFields.product);
            // 存在质保，并且配置了允许高级搜索
            if(taskFields.some(item => item.fieldName === 'quality' && item.isSearch === 1)){
              seoList.push(...qualityFields)
            }
          }
        }

      }
      // 自定义节点负责人信息
      if (this.isHaveNodeFlowAuth) {
        const targetIndex = seoList.findIndex(obj => obj.fieldName === 'reAllotUsers');
        
        if (targetIndex !== -1) {
          const taskNewFlowNodeUser = this.taskNewFlowNodeUser.map(field => {
            return {
              ...field,
              fieldName: `normal_${field.fieldName}`
            };
          });
          seoList.splice(targetIndex + 1, 0, ...taskNewFlowNodeUser);
        }
      }

      // if(hasQuality){
      //   const index = seoList.findIndex(({ fieldName }) => fieldName === 'product')
      //   index > -1 && seoList.splice(index + 1, 0, ...qualityFields);
      // }

      // // 添加固定条件
      // seoList.push();

      // 高级搜索添加系统服务商字段
      seoList.push(providerField)

      // 已存在 field
      const fieldsNameSet = new Set(seoList.map(field => field.fieldName));

      // common === 1
      const commonList = this.taskCommonFields.filter(item =>item.isSystem === 0 && item.isSearch === 1 && item.isCommon === 1);

      // 合并自定义节点fieldList数组的方法
      const mergedFieldList = this.taskNewFlowNode.flatMap(obj => obj?.fieldList).filter(item =>item.isSystem === 0 && item.isSearch === 1);

      // common === 0
      const withoutCommonFields = [...this.taskFields, ...this.taskReceiptFields].filter(item => (SpecifyFields.includes(item.fieldName) || item.isSystem === 0) && item.isSearch === 1 && item.isCommon === 0);

      const withoutCommonAndCommonList = cloneDeep([...withoutCommonFields, ...mergedFieldList,...commonList])
      withoutCommonAndCommonList.map(field => {
        // TODO:数坤单独做处理，因为数坤的客户关联字段-区域写死了fieldName为area，和工单系统字段area重复了，在高级搜索时会当成地址去搜索，所以改一下fieldName
        if (field.fieldName == 'area' && field.setting?.isShuKun && field.formType == 'relationCustomer') {
          field.fieldName = 'shuKunArea'
          field.field = 'shuKunArea'
        }
        return field
      })
      // 排序去重
      withoutCommonAndCommonList.sort((a, b) => a.orderId - b.orderId).forEach(field => !fieldsNameSet.has(field.fieldName) && (seoList.push(field))) // 添加进高级筛选列表中

      // seoList = seoList.filter(item => item.isSearch === 1)
      let seoListToUP = []
      seoList.forEach(seoItem => {
        seoItem.displayName = seoItem.displayName.charAt(0).toUpperCase() + seoItem.displayName.slice(1);
        // 服务商控件改名字为关联服务商
        if (seoItem.displayName == this.$t('common.base.serviceProvider') && seoItem.fieldName == 'serviceProviders') {
          seoItem.displayName = this.$t('common.fields.relationServiceProvider.displayName')
        }
        seoListToUP.push(seoItem)
      })
      this.seoSetList = seoListToUP;

      return seoList;
    },
    /**
     * @description 初始化page
     */
    initPage(pageNum = 1, pageSize = this.taskPage.pageSize) {
      this.taskPage.pageNum = pageNum;
      this.taskPage.pageSize = pageSize;
    },
    /**
     * @description 初始化参数
     * @param {Number} pageSize 页大小
     * @returns {Object} params
     */
    initParams(pageSize = 10, keyword) {
      return {
        keyword,
        pageNum: 1,
        pageSize,
        orderDetail: {},
        moreConditions: {
          conditions: [],
        },
      };
    },
    /**
     * @description 页码跳转
     * @param {Number} pageNum 页码
     */
    jump(pageNum) {
      this.taskPage.pageNum = pageNum;
      this.search();
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc, {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage()
    },
    /**
     * @description 打开外部链接
     * @param {Object} e 事件对象
     */
    openOutsideLink(e) {
      let url = e.target.getAttribute('url');
      if (!url) return;
      if (!/http/gi.test(url))
        return this.$platform.alert(i18n.t('common.base.tip.outsideLinkTip'));

      this.$platform.openLink(url);
    },
    /**
     * @description 打开已选中列表面板
     */
    openSelectionPanel() {
      this.$refs.openSelectionPanel.open();
    },
    /**
     *
     * @description 打开客户详情
     * @param {object} clientInfo 客户详情
     */
    openClientTab(clientInfo) {
      const {
        linkAuth,
        customerEntity
      } = clientInfo;
      const {
        id
      } = customerEntity;
      if (!linkAuth) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    openEventTab(clientInfo){
      let id = clientInfo.eventId;
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: id
      })
    },
    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(row, taskNo) {
      const taskId = row.id
      if (!taskId) return;

      let fromId = window.frameElement.getAttribute('id');

      // 纯草稿状态跳转编辑页面
      if (row.isDelete == 5 && row.inApprove == -1) {
        return openAccurateTab({
          type: PageRoutesTypeEnum.PageEditTask,
          key: taskId,
          params: 'noHistory=1',
          fromId
        })
      }

      if (!this.globalIsHaveTaskViewDetailAuth) return

      try {
        sessionStorage.setItem(
          taskId,
          JSON.stringify(
            this.taskPage.list.filter(item => (!(item.isDelete == 5 && item.inApprove == -1))).map(item => ({
              taskId: item.id,
              taskNo: item.taskNo,
            }))
          )
        );
      } catch (error) {
        console.error(error);
      }

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: `noHistory=1&JumpKey=${taskId}`,
        fromId
      })
    },
    /**
     * @description 打开用户详情tab
     * @param {String} userId 用户id
     */
    openUserTab(userId) {
      if (!userId) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: userId,
        params: 'noHistory=1&from=task',
        fromId
      })
    },

    /**
     * @description 重置参数
     */
    resetParams() {
      this.taskState = 'all'; // 重置 工单状态
      // this.taskStates.forEach(item => item.checked = item.value === 'all')
      this.exceptionNodes = 'all'; // 重置 异常节点
      this.visualAngle = 'all'; // 重置 创建视角
      this.currentTaskType = this.taskTypes[0]; // 重置 工单类型
      this.newSearchParams.keyword = ''; // 重置 keyword
      this.newSearchParams.searchCondition = ''; // 重置 关键词 索引条件
      this.newSearchParams.searchNodeId = ''; // 重置 自定义节点筛选
      this.provideType = ''; // 重置服务商类型
      this.initPage();
    },
    /**
     * 点击重置
     */
    handleReset(){
      // this.resetParams(); // 重置参数
      this.chooseView(); // 重置视图
      // this.search(); // 搜索
    },
    /**
     * @description 还原本地存储
     */
    async revertStorage() {
      const {
        pageSize,
        column_number
      } = await this.getIndexedDbData();
      const data = await this.getIndexedDbData();
      console.log('revertStorage', data)
      if(pageSize) {
        this.taskPage.pageSize = pageSize
      }
      if (column_number) this.columnNum = Number(column_number);
    },
    /**
     * @description 保存数据到本地存储
    */
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(TASK_LIST_KEY, JSON.stringify(data));
    },
    /**
     * @description 保存数据到本地indexedDB
    */
    async saveDataToIndexedDb(key, value) {
      const data = await this.getIndexedDbData()
      data[key] = value
      StorageUtil.storageSet(this.getTaskListStorageKey(), data, StorageModuleEnum.Task);
    },
    /**
     * 点击搜索按钮
     */
    handleSearch() {
      // this.$refs?.popperAdvancedSearchRef.search(); // 使用高级搜索内条件 需求确认 没有点击过高级搜索内的搜索按钮不用携带里面的条件数据
      this.initPage();
      this.search();
      this.trackEventHandler('search');
    },
    /**
     * @description 派单方式文案
     */
    allotTypeText(params) {
      let text;
      switch (params) {
      case 1:
        text = i18n.t('task.detail.components.manualDispatch');
        break;
      case 2:
        text = i18n.t('task.detail.components.poolDispatch');
        break;
      case 3:
        text = i18n.t('task.detail.components.autoDispatch');
        break;
      default:
        text = '';
        break;
      }
      return text;
    },
    /**
     * 选择创建视角
     */
    createPerspective(item){
      this.resetAdvancedConditions(); // 需求：切换快捷条件 高级搜索内保留条件但是搜索不携带
      this.visualAngle = item.value;
      this.initPage();
      this.search('save');
    },
    /* 异常搜索字段 */
    abnormalParams() {
      if (this.taskState === 'exception' && this.abnormalData.taskExceptionRange.length) {
        let exceptionStates = []
        this.abnormalData.taskExceptionRange.forEach(item => {
          if (item.switch) exceptionStates = [...exceptionStates, ...item.taskExceptionRangeValue]
        })
        let params = {
          exceptionNodes: this.exceptionNodes !== 'all' ? [this.exceptionNodes] : this.taskCustomExceptionNodeList.filter(item => {return item.englishName}).map(item => {return item.englishName}),
          isException: 1,
          exceptionStates
        }
        return params
      }
      return {}
    },

    /** 导出列 */
    _exportColumns() {
      let {
        taskFields,
        taskReceiptFields
      } = this
      // 工单列表导出字段中连接器来源和编号字段后端没做导出先隐藏
      taskFields = taskFields.filter(item=> item.fieldName != 'sourceTemplateName' && item.fieldName != 'sourceBizNo')
      // 工单信息
      let taskSelfFields = [];
      // 回执信息
      let taskReceiptSystemFields = [
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'spare_name',
          field: 'spare_name',
          displayName: i18n.t('common.base.sparePart'),
          label: i18n.t('common.base.sparePart'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'apply_material',
          field: 'apply_material',
          displayName: i18n.t('common.form.type.materialVerifyEliminate'),
          label: i18n.t('common.form.type.materialVerifyEliminate'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'return_material',
          field: 'return_material',
          displayName: i18n.t('common.form.type.materialReturn'),
          label: i18n.t('common.form.type.materialReturn'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'service_name',
          field: 'service_name',
          displayName: i18n.t('common.form.type.serviceIterm'),
          label: i18n.t('common.form.type.serviceIterm'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'balance_total',
          field: 'balance_total',
          displayName: i18n.t('task.list.displayName.feeInfo'),
          label: i18n.t('task.list.displayName.feeInfo'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
      ];
      // 服务商信息
      let taskProviderFields = this.isTaskExportProviderSettlement ? [
        {
          label: i18n.t('task.providerInfo'),
          value: 'providerFields',
          columns: providerFields.map(item => {
            item.export = true
            item.label = item.displayName
            return item
          }),
        }
      ] : []
      // 子表单信息(服务商)
      let taskSubFormFieldList = []

      // 子表单信息--回执信息
      let taskReceiptSubFormFieldList = []

      // 开启云仓灰度 则显示物料核销物料返还
      if(!this.isCloudwarehouse) {
        taskReceiptSystemFields = taskReceiptSystemFields.filter(item => item.fieldName !== 'apply_material' && item.fieldName !== 'return_material')
      }

      // 工单信息逻辑
      let linkman_list = '',
        address_list = '',
        product_list = ''
      taskSelfFields = taskFields.filter(field => filterTaskExportFieldWithFormType(field))
      // TODO displayName判断改为fieldName判断
      if (taskFields.length) {
        let first = taskFields.filter(item => {
          return item.fieldName === 'customer'
        })[0]
        if (first.setting.customerOption.linkman) {
          linkman_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmName',
            displayName: i18n.t('common.base.contact'),
            exportAlias: 'customerLinkman',
            formType: 'select',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            show: true,
            guideProfessions: [],
            isGuideData: false,
            guideData: false,
          },
          {
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmPhone',
            exportAlias: 'customerPhone',
            displayName: i18n.t('common.base.phone'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.address) {
          address_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'taddress',
            exportAlias: 'customerAddress',
            displayName: i18n.t('common.form.type.customerAddress'),
            formType: 'address',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.product) {
          product_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'product',
            exportAlias: 'product',
            displayName: i18n.t('common.base.product'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
      }
      taskSelfFields.forEach((item, index) => {
        if (item.fieldName === 'taskNo') {
          taskSelfFields.splice(index + 1, 0, {
            id: 476,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'templateName',
            exportAlias: 'templateName',
            displayName: i18n.t('common.task.taskType'),
            formType: 'text',
            defaultValue: null,
            isNull: 0,
            isSearch: 1,
            placeHolder: null,
            setting: {
              customerNameDuplicate: false,
            },
            orderId: 0,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          })
        }
      })
      taskSelfFields.forEach((item, index) => {
        if (item.fieldName === 'customer') {
          if (linkman_list) {
            taskSelfFields.splice(index + 1, 0, linkman_list[0], linkman_list[1])
          }
          if (address_list) {
            taskSelfFields.splice(index + linkman_list.length + 1, 0, address_list[0])
          }
          if (product_list) {
            taskSelfFields.splice(index + linkman_list.length + address_list.length + 1, 0, product_list[0])
          }
        }
      })


      // 处理质保信息
      if(taskSelfFields.filter(item => item.fieldName === 'quality').length){
        taskSelfFields = taskSelfFields.filter(item => item.fieldName !== 'quality')
        taskSelfFields.forEach((item, index)=>{
          if(item.fieldName === 'product'){
            taskSelfFields.splice(index + 1, 0, qualityFields[0], qualityFields[1], qualityFields[2])
          }

        })
      }

      // 过滤 故障库 服务商字段
      taskSelfFields = taskSelfFields.filter(item => !['faultLibrary', 'serviceProviders'].includes(item.fieldName))

      // 公共字段放入工单信息
      if(!this.currentTaskType.id) { // 工单类型-全部 导出不需要按orderid排序
        taskSelfFields = [...taskSelfFields.filter(item=>!item.isCommon), ...this.commonFields];
      } else {
        // taskSelfFields = [...taskSelfFields.filter(item=>!item.isCommon), ...this.commonFields].sort((a, b) => a.orderId - b.orderId);
      }

      taskSelfFields.map(item => {
        item.label = item.displayName
        item.export = true
        return item
      })

      if(taskSelfFields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        taskSelfFields = taskSelfFields.filter(item => item.formType !== 'relationForm')
      }


      // 回执信息逻辑
      const receiptFilterFields = ['sparepart', 'serviceIterm', 'materialReturn', 'materialVerifyEliminate', FieldTypeMappingEnum.JsCodeBlock]
      // 海伦哲特殊字段不允许被过滤
      const exportFieldBanFilterArr = this.isHandlerGray ? [FieldTypeMappingEnum.Attachment] : [];
      let taskReceiptFields_ = taskReceiptFields.filter(field => {
        return filterTaskExportFieldWithFormType(field, exportFieldBanFilterArr) && !receiptFilterFields.includes(field.formType)
      })
      taskReceiptSystemFields = [
        ...taskReceiptSystemFields,
        ...taskReceiptFields_
      ].map((field) => {
        field.export = true;
        if(this.isHandlerGray && exportFieldBanFilterArr.includes(field.formType)){
          field['filterIsBan'] = true
        }

        // 解析物流组件字段展示
        if(field.formType === 'logistics'){
          if(field.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsNo) > -1){
            field.label = i18n.t('common.base.logisticsNo')
          }

          if(field.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsCompany) > -1){
            field.label = i18n.t('common.base.logisticsCompany')
          }
        }
        return field;
      });

      if(taskReceiptSystemFields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        taskReceiptSystemFields = taskReceiptSystemFields.filter(item => item.formType !== 'relationForm')
      }

      // 系统信息
      let sysList = [...allExport, ...AbnormalList]
      // 自定义节点负责人信息
      if(this.isHaveNodeFlowAuth) {
        let targetIndex = sysList.findIndex(obj => obj.fieldName === 'synergies');
        
        if (targetIndex !== -1) {
          sysList.splice(targetIndex + 1, 0, ...this.taskNewFlowNodeUser);
        }
      }


      // 故障库字段
      if(this.isFaultGrayscale) {
        sysList = [...sysList, ...FaultLibrary]
      }

      // 基础版过滤产品、支付方式、结算时间、结算人、关联事件、曾打印字段
      if (this.isBasicEditionHideProduct) {
        taskSelfFields = taskSelfFields.filter(item => item.fieldName !== 'product')
      }
      if (this.isBasicEditionHidePay) {
        sysList = sysList.filter(item => item.fieldName !== 'balanceTime' && item.fieldName !== 'paymentMethod' && item.exportAlias !== 'balanceUser')
      }
      if (this.isBasicEditionHideEvent) {
        sysList = sysList.filter(item => item.fieldName !== 'eventNo')
      }
      if (this.isBasicEditionHidePrintTask) {
        sysList = sysList.filter(item => item.exportAlias !== 'oncePrinted')
      }
      // 基础版导出列的系回执信息过滤备件、服务项目、费用信息字段
      const filterEnum = {
        'spare_name':()=>{
          return !this.isBasicEditionHidePart
        },
        'service_name':()=>{
          return !this.isBasicEditionHideServe
        },
        'balance_total':()=>{
          return !this.isBasicEditionHidePay
        }
      }
      taskReceiptSystemFields = taskReceiptSystemFields.filter(field => {
        try{
          if(!Reflect.has(filterEnum, field.fieldName)) return true
          return filterEnum[field.fieldName];
        }catch(err){
          console.warn('taskReceiptSystemFields.filter try catch err')
          return true
        }
      })
      // 导出子表单（服务商）
      taskSubFormFieldList = this.getSubFormFieldList(taskFields)
      // 导出子表单（回执表单）
      taskReceiptSubFormFieldList = this.getSubFormFieldList(taskReceiptFields, true)

      if(!this.isServiceProviderSubForm) {
        taskSubFormFieldList = taskSubFormFieldList.filter(item => item.fieldName !== 'serviceProviders')
      }

      this.exportColumns = [
        {
          label: this.isHaveNodeFlowAuth ? i18n.t('task.taskNewTaskInfo') : i18n.t('task.taskInfo'),
          value: 'taskChecked',
          columns: taskSelfFields,
        },
        ...this.taskNewFlowExportField,
        {
          label: i18n.t('task.receiptInfo'),
          value: 'receiptChecked',
          columns: taskReceiptSystemFields,
        },
        {
          label: i18n.t('task.systemInfo'),
          value: 'systemChecked',
          columns: sysList.map(item => {
            item.export = true
            item.label = item.displayName
            return item
          }),
        },
        ...taskProviderFields,
        ...taskSubFormFieldList,
        ...taskReceiptSubFormFieldList,
      ];
      this.getCardDetailList(this.currentTaskType.id);
    },

    // 获取子表单的字段
    getSubFormFieldList(fields, isReceipt) {
      let allSubFormList = []
      fields.forEach(item => {
        if(item?.setting?.isSubForm && (item.subFormFieldList && item.subFormFieldList.length > 0)) {
          let columns = item.subFormFieldList || []
          columns.forEach(sub => {
            sub.value = sub.fieldName
            sub.label = sub.displayName
            sub.field = sub.fieldName
            sub.export = true
          })

          allSubFormList.push({
            value: item.fieldName,
            label: isReceipt ? `${i18n.t('task.list.zhongqiText.receiptInfo')}：${item.displayName}` : item.displayName ,
            columns
          })
        }
      })
      return allSubFormList
    },

    /**
     * @description 已选择面板数据变化
     */
    selectionPanelInputChange(value) {
      this.multipleSelection = value.slice();
    },
    /**
     * @description 已选择面板移除某一项
     */
    selectionPanelRemoveItem({
      selection,
      item
    }) {
      selection.length < 1
        ? this.toggleSelection()
        : this.toggleSelection([item]);
    },
    /**
     * @description 计算已选择
     * @param {Array} selection 已选择列表
     * @return {Array} 计算过滤后的列表
     */
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
        this.taskPage.list.every((c) => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    /**
     * @description 显示最后一次更新记录
     * @param {Object} row 行数据
     */
    showLatestUpdateRecord(row) {
      if (row.latesetUpdateRecord) return;

      TaskApi.getTaskUpdateRecord({
        taskId: row.id
      })
        .then((res) => {
          if (!res || res.status) return;

          this.taskPage.list.forEach((c) => {
            if (c.id === row.id) {
              this.$set(c, 'latesetUpdateRecord', res.data);
            }
          });
        })
        .catch((e) => console.error('e', e));
    },
    /**
     * @description 打开选择列设置
     */
    showColumnsSetting() {
      this.trackEventHandler('columns');
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    /**
     * @description 排序变化
     * @param {Object} option 配置
     */
    sortChange(option) {
      const UserNameConvertMap = {
        'createUserName': 'createUser',
        'executorName': 'executorUser',
        'customer': 'customerName',
        'qualityStartTime': 'qualityStartTime',
        'qualityEndTime': 'qualityEndTime'
      }

      try {
        let {
          prop,
          order
        } = option;

        if (!order) {
          this.sortModel = null;
          return this.search();
        }
        const sortedField = this.taskListFields.filter((sf) => sf.fieldName === prop)[0] || {};

        let isSystem = 0;
        let isConvertedProp = Object.keys(UserNameConvertMap).indexOf(prop) > -1

        if (prop === 'createTime' || prop === 'updateTime' || isConvertedProp) {
          isSystem = 1;
        } else {
          isSystem = sortedField.isSystem;
        }

        if (isConvertedProp) {
          prop = UserNameConvertMap[prop]
        }

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          // column: isSystem ? `task.${prop}` : prop,
          column: prop,
        };

        if (
          prop === 'createTime'
          || prop === 'updateTime'
          || sortedField.formType === 'date'
          || sortedField.formType === 'datetime'
        ) {
          sortModel.type = 'date';
        } else if (prop === 'level' || prop === 'taskNo') {
          sortModel.type = 'string';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.sortModel = sortModel;
        this.initPage();
        this.search();
      } catch (e) {
        console.error('e', e);
      }
    },
    /**
     * @description 选择项切换
     * @param {Array<Row>} rows 行
     */
    toggleSelection(rows = []) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (Array.isArray(rows) && rows.length > 0) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.taskPage.list.every((item) => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    /**
     * @description TalkingData事件埋点
     * @param {String} type The constant TRACK_EVENT_MAP of the keys
     */
    trackEventHandler(type = '') {
      let eventName = TRACK_EVENT_MAP[type];
      if (!eventName) return;
      window.TDAPP.onEvent(eventName);
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || []
      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage()
        this.$message.success(i18n.t('common.base.saveSuccess'));
        // 把选中数据的选中状态再次渲染到表格上面去
        if (this.multipleSelection.length) {
          this.$nextTick(() => {
            this.multipleSelection.forEach(item => {
              this.taskPage.list.forEach(v => {
                if (v.id === item.id) {
                  this.$refs.multipleTable.toggleRowSelection(v, true);
                }
              })
            })
          })
        }
      })
    },
    async saveColumnStatusToStorage() {
      const localStorageData = await this.getIndexedDbData();
      let columnsStatus = null

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      const saveKey = this.getTaskListStorageKey()

      if(localStorageData[saveKey]){
        try{
          localStorageData[saveKey] = columnsList;
          columnsStatus = localStorageData[saveKey];
        }catch(err){
          console.error(err)
        }
      }else if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }
      if(saveKey){
        this.saveDataToIndexedDb(saveKey, columnsStatus)
      }else{
        this.saveDataToIndexedDb('columnStatus', columnsStatus); // 默认选择列保存
      }
    },
    /**
     * @description 批量创建服务报告
    */
    batchCreateServiceReport() {
      let taskIds = this.getTaskIdsForBatchReport()
      // 验证
      if (taskIds.length <= 0) {
        return this.$platform.alert(i18n.t('task.tip.taskListTip9'))
      }
      // 构建参数
      let params = { isPdf: true, taskIds }
      // 创建下载
      createServiceReportBatch(params)
        .then(result => {
          // this.$platform.alert(result.message || '')
          // // 打开后台任务弹窗
          // window.parent.showExportList()
          // window.parent.exportPopoverToggle(true)
          if(result.status === 0){
            exportAlert(result.message);
          }else {
            this.$platform.alert(result.message || '');
          }
        })
        .catch(err => {
          console.error(err)
        })
    },
    /**
     * @description 批量打印工单
    */



    batchPrintServiceReport() {
      let taskIds =  this.multipleSelection?.filter(task => task.state !== TaskStateEnum.DRAFT.value)?.map(task => task.id) ?? []

      // 验证
      if (taskIds.length <= 0) {
        return this.$platform.alert(i18n.t('task.tip.taskListTip10'))
      }
      // 构建参数
      let params = { taskIds }
      // 打印
      createServicePrintBatch(params)
        .then(result => {
          // this.$platform.alert(result.message || '')
          // // 打开后台任务弹窗
          // window.parent.showExportList()
          // window.parent.exportPopoverToggle(true)
          if(result.status === 0){
            exportAlert(result.message);
          }else {
            this.$platform.alert(result.message || '');
          }
        })
        .catch(err => {
          console.error(err)
        })
    },
    /** @return 人员userId和展示字段 */
    presonDisplayObj(attr, fieldName, row) {
      let obj = {};
      switch(fieldName) {
      case 'createUserName':
        obj = row.createUser;
        break;
      case 'executorName':
        obj = row.executorUser;
        break;
      case 'allotName':
        obj = row.allotUser;
        break;
      default:
        break;
      }

      obj = obj || {};

      return obj[attr];
    },
    getTaskIdsForBatchReport() {
      let finishedStates = [TaskStateEnum.FINISHED.value, TaskStateEnum.COSTED.value, TaskStateEnum.CLOSED.value]

      return (
        this.multipleSelection
          .filter(task => {
            return finishedStates.indexOf(task.state) >= 0
          })
          .map(task => task.id)
      )
    },
    /**
     * @des 查询是否有查询参数
     */
    findFastPageData(data){
      return new Promise((resolve, reject)=>{
        try {
          let parseData = sessionStorageGet(`bbx-faster-${pageTaskList.type}`);
          if(!data && !parseData) return resolve()
          sessionStorageRemove(`bbx-faster-${pageTaskList.type}`);
          // 解析参数
          const { filterData } = data || JSON.parse(parseData);
          const state = (filterData ? filterData.state : 'all').replace(/Id/g, '');
          if(state && this.taskStates.some(item => item.value === state)){
            // 传入state且在taskStateList中存在 选中此工单状态
            // chooseTaskState(this.taskStates.find(item => item.checked = item.value === state))
            this.taskState = state;
          }
          // this.fasterFilterList(filterData);
        } catch (error) {
          console.warn(error, 'findFastPageData error try catch');
          resolve()
        }
      })
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight(){
      let min = TABLE_HEIGHT_MIN;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 16 - 10;
        // console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        // console.log(pxArray, 'pxArray')
        min = min > TABLE_HEIGHT_MIN ? min : TABLE_HEIGHT_MIN;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    /**
     * @desc 收起padding-bttom为0
     */
    changePadding(_distance) {
      this.$nextTick(() => {
        this.$set(this, 'headerPaddingTop', `${_distance}px`);
      });
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.updateListHeight();
    },

    updateListHeight() {
      this.packUp ? this.changePadding(16) : this.changePadding(0)
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    /**
     * @des 获取系统内的灰度
     */
    getSystemGrayInfo(){
      getAllGrayInfo().then(res=>{
        this.allGrayInfo = res;
      })
    },

    // 切换工单状态 --> 单选
    chooseTaskState(state) {
      // 多选方案
      // this.taskStates.forEach(item => item.checked = state === item); // 除了当前state的checked都设为false
      // 单选方案
      this.taskState = state.value; // 工单状态
      this.exceptionNodes = 'all'; // 恢复全部
      if(this.isHaveNodeFlowAuth) {
        this.newSearchParams.searchNodeId = state?.nodeType == 'normal' ? state.value : '' // 自定义节点
      }
      this.resetAdvancedConditions(); // 需求：切换快捷条件 高级搜索内保留条件但是搜索不携带

      this.initPage()
      this.search('save');
      this.buildColumns();
    },

    // 重置高级搜索条件
    resetAdvancedConditions(){
      this.conditionParams = {
        conditions: [],
        systemConditions: [],
      };
      // this.$refs.popperAdvancedSearchRef.setButtonStatus(false)
    },

    // 高级搜索 ——> 点击搜索按钮
    async handleAdvancedSearch({searchModel = [],isShowSave = false,searchList = []}) {
      this.conditionParams = searchModel;
      let searchParamsPeer = isShowSave;
      // 切换视角后，初始化isFlagSaveStatus为false
      if(!isShowSave) {
        this.isFlagSaveStatus = false;
      };
      this.searchList = searchList;
      // minix,混入名为baseSaveShowHandle
      searchParamsPeer = this.handleShowSave(searchList,'task')
      this.initPage();
      // const formData = this.$refs.popperCommonAdvancedSearchFromRef.getData();
      // this.changeAdvancedSearchCommonForm(formData);
      await this.search();
      if(this.$refs.taskSaveRef && typeof this.$refs.taskSaveRef.open === 'function') {
        this.$refs.taskSaveRef.open(searchParamsPeer, searchList);
      };
    },
    /** 处理删除后搜索条件的变化 */
    // handleDeleteSearchModal(searchList) {
    //   console.log('searchList',searchList);
    //   this.searchList = searchList;
    //   this.$refs.taskSaveRef.open(this.isFlagSaveStatus, this.searchList)
    // },
    // 生成搜索条件
    buildSearchParams() {
      const { newSearchParams, taskState, conditionParams, visualAngle, initData, currentTaskType, sortModel, provideType, taskPage } = this;
      const searchParams = {
        page: taskPage.pageNum,
        pageSize: taskPage.pageSize,
        queryCreateHalf: true, // 是否查询草稿，只有工单列表才查询，其它调用工单列表查询接口的地方不查询草稿
        ...newSearchParams,
        ...conditionParams, // 高级搜索条件
        stateList: statesMap[taskState] || [], // 工单状态
        ...this.abnormalParams(), // 异常工单
        templateId: currentTaskType ? currentTaskType.id : null, // 工单类型
        searchCondition: newSearchParams.searchCondition || undefined,
        // sorts: {}, // 排序
      };
      // 草稿状态搜索参数使用isDelete = 5
      if (taskState == 'draft') {
        searchParams.isDelete = 5
      }

      // 创建视角
      if(visualAngle !== 'all'){
        searchParams[visualAngle] = initData.currentUserId
      }else if(provideType) { //  由于provideType条件和visualAngle是互斥的，只要选了创建视角，provideType就不在传递（provideType只有在创建视角是all的情况才传递）
        searchParams[provideType] = true
      }

      // 排序
      if(sortModel){
        const { column, isSystem, sequence } = sortModel;
        searchParams.sorts = [{
          property: isSystem ? column : `attribute.${column}`,
          direction: sequence,
        }, ];
      }

      return searchParams;
    },

    async search(type = 'task') {
      this.$nextTick(()=>{
        // 滚动至表格顶部
        this.$refs.multipleTable?.$refs?.bodyWrapper?.scrollTo(0, 0)
      })
      const params = this.buildSearchParams();
      try {
        // 地图模式时触发地图模式搜索
        if (this.mapShow && this.$refs.taskMap) {
          this.$refs.taskMap.init()
        }
        // loading 返回
        // if(this.loading) return;
        this.loading = true;
        const result = await searchApi(params);
        let isSuccess = result?.success === true;
        if (!isSuccess) {
          this.$platform.alert(result?.message);
          this.initPage();
          return;
        }

        let data = result?.result || {};
        let { number, content, totalPages, totalElements, size } = data;

        data['total'] = totalPages || 1;
        data['pageNum'] = number || 1;
        data['pageSize'] = size
        data['list'] = (content || []).map((item) => {
          item.pending = false;
          item.acceptUsedTime = this.timestamp(item.acceptUsedTime);
          item.taskUsedTime = this.timestamp(item.taskUsedTime);
          item.workUsedTime = this.timestamp(item.workUsedTime);
          item.taskResponseTime = this.timestamp(item.taskResponseTime);
          item.createToCompleteUsedTime = this.timestamp(item.createToCompleteUsedTime);
          // 草稿状态处理
          if (item.isDelete == 5) {
            item.state = 'draft'
          }
          if (item.planTime && this.planTimeType === 'date') {
            item.planTime = formatDate(safeNewDate(item.planTime), 'YYYY-MM-DD');
          }
          if (item.planStartTime && this.planStartTimeType === 'date') {
            item.planStartTime = formatDate(safeNewDate(item.planStartTime), 'YYYY-MM-DD');
          }
          if (item.planEndTime && this.planEndTimeType === 'date') {
            item.planEndTime = formatDate(safeNewDate(item.planEndTime), 'YYYY-MM-DD');
          }
          return item;
        });
        // 合并节点负责人
        if (this.isHaveNodeFlowAuth) {
          const content = data?.content || [];
          content.forEach(item => {
            const { attribute: { nodeHandlingPerson = {} } = {} } = item;
            Object.assign(item, nodeHandlingPerson);
          });
        }

        // let list = [...data.content, ...data.content, ...data.content, ...data.content, ...data.content, ...data.content]
        this.taskPage.merge(Page.as(data));
        this.taskPage['totalElements'] = totalElements;
        this.taskPage.list = disposeFormListViewTime(data?.content || [], this.columns) // data?.content || []
        this.taskPage.pageNum = number || 1;

        // 把选中的匹配出来
        // this.matchSelected();
        // console.log("工单列表渲染数据", this.taskPage);
        if (this.multipleSelection.length) {
          this.$nextTick(() => {
            this.multipleSelection.forEach(item => {
              this.taskPage.list.forEach(v => {
                if (v.id === item.id) {
                  this.$refs.multipleTable.toggleRowSelection(v);
                }
              })
            })
          })
        }

        this.$refs.taskListPage.scrollTop = 0;
        if(type === 'save') {
          // 处理默认视图特殊情况
          if(this.currentView && this.currentView.viewName !== '默认视图') {
            this.$refs.taskSaveRef.open(true, this.searchList);
          };
          this.isFlagSaveStatus = true;
        }
      } catch (error) {
        console.error('search fail', error);
        this.taskPage.list = [];
      } finally {
        this.loading = false;
        this.getTaskCountByState(); // 重新查询数量
        this.$nextTick(() => {
          this.knowTableContainerHeight()
        });
      }
    },

    /**
     * 从高级筛选中修改常用搜索字段
     */
    changeAdvancedSearchCommonForm(formData){
      const {taskState, visualAngle, taskType, exceptionNodes, provideType = ''} = formData;
      // const stateSet = new Set(taskState);
      // this.taskStates.forEach(item => item.checked = stateSet.has(item.value));
      this.taskState = taskState;
      this.visualAngle = visualAngle;
      this.exceptionNodes = exceptionNodes;
      this.provideType = provideType;

      if(taskType !== this.currentTaskType.id){
        // 切换工单字段 需要重新获取字段等
        const type = this.taskTypes.find(item => item.id === taskType);
        this.changeTaskType(type || {id: taskType}, false) // 粗略兼容工单类型没有的情况
        return;
      }
    },

    // 处理视图
    genViewport(_v){
      if(!_v || !_v.searchModel) return null
      const viewport = cloneDeep(_v);
      if(viewport?.searchModel[0]?.fieldName === 'taskCommonSearch'){
        // 外面固定条件截取
        const formData = viewport.searchModel.shift();
        viewport.shortcutConditions = formData.value;
      }
      return viewport
    },

    /**
     * 选择视图
     */
    chooseView(_v = null){
      this.resetParams(); // 重x置条件并搜索
      this.currentView = this.genViewport(_v); // 视图设为当前视图
      if(this.currentView?.shortcutConditions){
        // 外面固定条件截取
        this.changeAdvancedSearchCommonForm(this.currentView.shortcutConditions);
      }
      this.initialize(true, false).then(() => {
        // 切换视图 条件需要再字段更新之后
        this.viewportSearchModel = this.currentView?.searchModel || [];
      })
    },

    /**
     * 视图列表 点击 编辑/新建
     */
    editViewByViewport(_v){
      const viewport = this.genViewport(_v);
      this.shortcutConditions = viewport?.shortcutConditions || this.genShortcutConditions();
      this.$refs.advancedSearchModalRef.open(viewport);
    },

    /**
     * 高级筛选 点击 新建
     */
    createViewBySearchModel(searchModel) {
      this.shortcutConditions = this.genShortcutConditions();
      this.$refs.advancedSearchModalRef.open({ searchModel })
    },

    /**
     * 高级筛选 点击 保存
     */
    updateViewBySearchModel(searchModel) {
      this.shortcutConditions = this.genShortcutConditions();
      this.currentView.shortcutConditions = this.shortcutConditions;
      const viewportData = {
        ...this.currentView,
        searchModel,
      }
      this.$refs.advancedSearchModalRef.open(viewportData)
    },

    /**
     * 视图保存成功 更新选中视图
     * @param {Object} _v 视图信息
     */
    handleViewportSave(_v){
      if(!_v) return;
      this.chooseView(_v); // 选中当前视图
      this.$refs.viewportListRef.refresh(_v.viewId); // 刷新视图列表 并选中
    },

    // 生成快捷条件
    genShortcutConditions(){
      return {
        taskState: this.taskState,
        visualAngle: this.visualAngle,
        taskType: this.currentTaskType.id,
        exceptionNodes: this.exceptionNodes,
      }
    },

    // 保存视图之前，存入外部固定条件到视图中
    beforeSaveView(viewport){
      // const value = this.$refs.modelCommonAdvancedSearchFromRef.getData()
      const value = viewport?.shortcutConditions || this.genShortcutConditions();
      return [
        {fieldName: 'taskCommonSearch', operator: '', value },
      ]
    },

    /**
     * @description 新建工单
     */
    createTask({ id }) {
      this.$track.clickStat(this.$track.formatParams('TO_CREATE'));

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type:PageRoutesTypeEnum.PageCreateTask,
        titleKey: i18n.t('task.createTask'),
        params:`defaultTypeId=${id}`,
        fromId
      })
    },

    /**
     * 计算折叠
     */
    calcCollapse: debounce(function (){
      const {taskStateListRef: stateEl, taskTypeListRef: typeEl} = this.$refs
      if(stateEl) {
        // 工单状态 折叠计算
        const height = stateEl.offsetHeight;
        this.taskStateNeedCollapse = height > 40; // 工单状态是否需要折叠
        if(!this.taskStateNeedCollapse && this.taskStateCollapse) {
          // 如果不允许折叠且打开状态需要全部展示
          this.taskStateCollapse = false; // 工单状态展开
        }
      }

      if(typeEl) {
        // 工单类型 折叠计算
        const height = typeEl.offsetHeight;
        this.taskTypeNeedCollapse = height > 40; // 工单状态是否需要折叠
        if(!this.taskTypeNeedCollapse && this.taskTypeCollapse) {
          // 如果不允许折叠且打开状态需要全部展示
          this.taskTypeCollapse = false; // 工单类型展开
        }
      }
    }, 500),

    /**
     * 常用字段切换
     * @param {*} fieldName
     * @param {*} isChecked
     */
    changeCommonUse({fieldName, isChecked}){
      const inCommonUseSet = new Set(this.inCommonUse)
      if(isChecked){
        inCommonUseSet.add(fieldName)
      }else {
        inCommonUseSet.delete(fieldName);
      }
      this.inCommonUse = Array.from(inCommonUseSet);

      const storageKey = 'advanced-search-commonUse';
      try {
        StorageUtil.storageSet(storageKey, this.inCommonUse, StorageModuleEnum.Task)
      } catch (error) {
        console.error('changeCommonUse ~ setIndexedDbData ~ error', error)
      }
    },

    /**
     * 恢复常用字段
     */
    async recoverCommonUse(){
      const storageKey = 'advanced-search-commonUse';
      try {
        this.inCommonUse = await StorageUtil.storageGet(storageKey, [], StorageModuleEnum.Task)
      } catch (error) {
        console.error('recoverCommonUse ~ getIndexedDbData ~ error', error)
        return Promise.reject(error)
      }
    },

    handleFilterClick(payload, type) {
      this.$track.clickStat(this.$track.formatParams('QUICK_SEARCH', type));

      if(type === '状态视角') {
        this.chooseTaskState(payload);
      } else if(type === '创建视角') {
        this.createPerspective(payload);
      } else if(type === '工单类型') {
        this.changeTaskType(payload);
      }
      // 重置列表排序条件
      this.sortModel = null
    },
    // 呼叫中心来源数据
    callCenterSourceData(scope){
      return {
        sourceTypeId:scope.row.id,
        sourceType:'task',
        sourceTypeNo:scope.row.taskNo
      }
    },
  },
  components: {
    [TaskMap.name]: TaskMap,
    [TaskTransfer.name]: TaskTransfer,
    [BatchEditingCustomerDialog.name]: BatchEditingCustomerDialog,
    AdvancedSearch, // 高级筛选
    AdvancedSearchModal, // 视图编辑弹框
    ViewportDropdown, // 视图下拉
    TaskCommonAdvancedSearchForm, // 高级搜索内联动外部搜索条件
    statisticalDialog,
    [SpareStatisticDialog.name]: SpareStatisticDialog,
  },
};
